From 0b9c4c18dd96197c6f6c2dc80170aecfada72595 Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Mon, 9 Dec 2024 09:25:45 -0600 Subject: [PATCH 01/19] Refactor event cleanup to consider review severity (#15415) * Keep track of objects max review severity * Refactor cleanup to split snapshots and clips * Cleanup events based on review severity * Cleanup review imports * Don't catch detections --- .../api/defs/query/review_query_parameters.py | 2 +- frigate/api/defs/response/review_response.py | 2 +- frigate/api/review.py | 2 +- frigate/events/cleanup.py | 199 +++++++++++++----- frigate/events/maintainer.py | 1 + frigate/object_processing.py | 25 +-- frigate/review/maintainer.py | 7 +- frigate/review/types.py | 6 + frigate/test/http_api/base_http_test.py | 2 +- frigate/test/http_api/test_http_review.py | 2 +- frigate/track/tracked_object.py | 23 ++ 11 files changed, 187 insertions(+), 84 deletions(-) create mode 100644 frigate/review/types.py diff --git a/frigate/api/defs/query/review_query_parameters.py b/frigate/api/defs/query/review_query_parameters.py index 4361d313cf..ee9af740e6 100644 --- a/frigate/api/defs/query/review_query_parameters.py +++ b/frigate/api/defs/query/review_query_parameters.py @@ -3,7 +3,7 @@ from pydantic import BaseModel from pydantic.json_schema import SkipJsonSchema -from frigate.review.maintainer import SeverityEnum +from frigate.review.types import SeverityEnum class ReviewQueryParams(BaseModel): diff --git a/frigate/api/defs/response/review_response.py b/frigate/api/defs/response/review_response.py index 39e078b215..b2fed3b1a6 100644 --- a/frigate/api/defs/response/review_response.py +++ b/frigate/api/defs/response/review_response.py @@ -3,7 +3,7 @@ from pydantic import BaseModel, Json -from frigate.review.maintainer import SeverityEnum +from frigate.review.types import SeverityEnum class ReviewSegmentResponse(BaseModel): diff --git a/frigate/api/review.py b/frigate/api/review.py index 56bd937bc6..e5692f009a 100644 --- a/frigate/api/review.py +++ b/frigate/api/review.py @@ -26,7 +26,7 @@ ) from frigate.api.defs.tags import Tags from frigate.models import Recordings, ReviewSegment -from frigate.review.maintainer import SeverityEnum +from frigate.review.types import SeverityEnum from frigate.util.builtin import get_tz_modifiers logger = logging.getLogger(__name__) diff --git a/frigate/events/cleanup.py b/frigate/events/cleanup.py index 5400cc660c..b1b485c3d2 100644 --- a/frigate/events/cleanup.py +++ b/frigate/events/cleanup.py @@ -4,7 +4,6 @@ import logging import os import threading -from enum import Enum from multiprocessing.synchronize import Event as MpEvent from pathlib import Path @@ -16,11 +15,6 @@ logger = logging.getLogger(__name__) -class EventCleanupType(str, Enum): - clips = "clips" - snapshots = "snapshots" - - CHUNK_SIZE = 50 @@ -67,19 +61,11 @@ def get_camera_labels(self, camera: str) -> list[Event]: return self.camera_labels[camera]["labels"] - def expire(self, media_type: EventCleanupType) -> list[str]: + def expire_snapshots(self) -> list[str]: ## Expire events from unlisted cameras based on the global config - if media_type == EventCleanupType.clips: - expire_days = max( - self.config.record.alerts.retain.days, - self.config.record.detections.retain.days, - ) - file_extension = None # mp4 clips are no longer stored in /clips - update_params = {"has_clip": False} - else: - retain_config = self.config.snapshots.retain - file_extension = "jpg" - update_params = {"has_snapshot": False} + retain_config = self.config.snapshots.retain + file_extension = "jpg" + update_params = {"has_snapshot": False} distinct_labels = self.get_removed_camera_labels() @@ -87,10 +73,7 @@ def expire(self, media_type: EventCleanupType) -> list[str]: # loop over object types in db for event in distinct_labels: # get expiration time for this label - if media_type == EventCleanupType.snapshots: - expire_days = retain_config.objects.get( - event.label, retain_config.default - ) + expire_days = retain_config.objects.get(event.label, retain_config.default) expire_after = ( datetime.datetime.now() - datetime.timedelta(days=expire_days) @@ -162,13 +145,7 @@ def expire(self, media_type: EventCleanupType) -> list[str]: ## Expire events from cameras based on the camera config for name, camera in self.config.cameras.items(): - if media_type == EventCleanupType.clips: - expire_days = max( - camera.record.alerts.retain.days, - camera.record.detections.retain.days, - ) - else: - retain_config = camera.snapshots.retain + retain_config = camera.snapshots.retain # get distinct objects in database for this camera distinct_labels = self.get_camera_labels(name) @@ -176,10 +153,9 @@ def expire(self, media_type: EventCleanupType) -> list[str]: # loop over object types in db for event in distinct_labels: # get expiration time for this label - if media_type == EventCleanupType.snapshots: - expire_days = retain_config.objects.get( - event.label, retain_config.default - ) + expire_days = retain_config.objects.get( + event.label, retain_config.default + ) expire_after = ( datetime.datetime.now() - datetime.timedelta(days=expire_days) @@ -206,19 +182,143 @@ def expire(self, media_type: EventCleanupType) -> list[str]: for event in expired_events: events_to_update.append(event.id) - if media_type == EventCleanupType.snapshots: - try: - media_name = f"{event.camera}-{event.id}" - media_path = Path( - f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}" - ) - media_path.unlink(missing_ok=True) - 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}") + try: + media_name = f"{event.camera}-{event.id}" + media_path = Path( + f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}" + ) + media_path.unlink(missing_ok=True) + 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 + for i in range(0, len(events_to_update), CHUNK_SIZE): + batch = events_to_update[i : i + CHUNK_SIZE] + logger.debug(f"Updating {update_params} for {len(batch)} events") + Event.update(update_params).where(Event.id << batch).execute() + + return events_to_update + + def expire_clips(self) -> list[str]: + ## Expire events from unlisted cameras based on the global config + expire_days = max( + self.config.record.alerts.retain.days, + self.config.record.detections.retain.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] = ( + 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(list(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( + 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, + ) + + events_to_update = [] + + for batch in query.iterator(): + events_to_update.extend([event.id for event in batch]) + if len(events_to_update) >= CHUNK_SIZE: + logger.debug( + f"Updating {update_params} for {len(events_to_update)} events" + ) + Event.update(update_params).where( + Event.id << events_to_update + ).execute() + events_to_update = [] + + # Update any remaining events + if events_to_update: + logger.debug( + f"Updating clips/snapshots attribute for {len(events_to_update)} events" + ) + Event.update(update_params).where(Event.id << events_to_update).execute() + + events_to_update = [] + now = datetime.datetime.now() + + ## Expire events from cameras based on the camera config + for name, camera in self.config.cameras.items(): + expire_days = max( + camera.record.alerts.retain.days, + camera.record.detections.retain.days, + ) + alert_expire_date = ( + now - datetime.timedelta(days=camera.record.alerts.retain.days) + ).timestamp() + detection_expire_date = ( + now - datetime.timedelta(days=camera.record.detections.retain.days) + ).timestamp() + # grab all events after specific time + expired_events = ( + Event.select( + Event.id, + Event.camera, + ) + .where( + Event.camera == name, + Event.retain_indefinitely == False, + ( + ( + (Event.data["max_severity"] != "detection") + | (Event.data["max_severity"].is_null()) + ) + & (Event.end_time < alert_expire_date) + ) + | ( + (Event.data["max_severity"] == "detection") + & (Event.end_time < detection_expire_date) + ), + ) + .namedtuples() + .iterator() + ) + + # delete the grabbed clips from disk + # only snapshots are stored in /clips + # so no need to delete mp4 files + for event in expired_events: + events_to_update.append(event.id) # update the clips attribute for the db entry for i in range(0, len(events_to_update), CHUNK_SIZE): @@ -230,8 +330,9 @@ def expire(self, media_type: EventCleanupType) -> list[str]: def run(self) -> None: # only expire events every 5 minutes - while not self.stop_event.wait(300): - events_with_expired_clips = self.expire(EventCleanupType.clips) + while not self.stop_event.wait(1): + events_with_expired_clips = self.expire_clips() + return # delete timeline entries for events that have expired recordings # delete up to 100,000 at a time @@ -242,7 +343,7 @@ def run(self) -> None: Timeline.source_id << deleted_events_list[i : i + max_deletes] ).execute() - self.expire(EventCleanupType.snapshots) + self.expire_snapshots() # drop events from db where has_clip and has_snapshot are false events = ( diff --git a/frigate/events/maintainer.py b/frigate/events/maintainer.py index 3a4209ec3b..e2b9245d6e 100644 --- a/frigate/events/maintainer.py +++ b/frigate/events/maintainer.py @@ -210,6 +210,7 @@ def handle_object_detection( "top_score": event_data["top_score"], "attributes": attributes, "type": "object", + "max_severity": event_data.get("max_severity"), }, } diff --git a/frigate/object_processing.py b/frigate/object_processing.py index ef23c3de3f..b5196e6862 100644 --- a/frigate/object_processing.py +++ b/frigate/object_processing.py @@ -702,30 +702,7 @@ def should_retain_recording(self, camera: str, obj: TrackedObject): return False # If the object is not considered an alert or detection - review_config = self.config.cameras[camera].review - if not ( - ( - obj.obj_data["label"] in review_config.alerts.labels - and ( - not review_config.alerts.required_zones - or set(obj.entered_zones) & set(review_config.alerts.required_zones) - ) - ) - or ( - ( - not review_config.detections.labels - or obj.obj_data["label"] in review_config.detections.labels - ) - and ( - not review_config.detections.required_zones - or set(obj.entered_zones) - & set(review_config.detections.required_zones) - ) - ) - ): - logger.debug( - f"Not creating clip for {obj.obj_data['id']} because it did not qualify as an alert or detection" - ) + if obj.max_severity is None: return False return True diff --git a/frigate/review/maintainer.py b/frigate/review/maintainer.py index de137cb268..8aa0f65e0f 100644 --- a/frigate/review/maintainer.py +++ b/frigate/review/maintainer.py @@ -7,7 +7,6 @@ import string import sys import threading -from enum import Enum from multiprocessing.synchronize import Event as MpEvent from pathlib import Path from typing import Optional @@ -27,6 +26,7 @@ from frigate.events.external import ManualEventState from frigate.models import ReviewSegment from frigate.object_processing import TrackedObject +from frigate.review.types import SeverityEnum from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop logger = logging.getLogger(__name__) @@ -39,11 +39,6 @@ THRESHOLD_DETECTION_ACTIVITY = 30 -class SeverityEnum(str, Enum): - alert = "alert" - detection = "detection" - - class PendingReviewSegment: def __init__( self, diff --git a/frigate/review/types.py b/frigate/review/types.py new file mode 100644 index 0000000000..0046f9b699 --- /dev/null +++ b/frigate/review/types.py @@ -0,0 +1,6 @@ +from enum import Enum + + +class SeverityEnum(str, Enum): + alert = "alert" + detection = "detection" diff --git a/frigate/test/http_api/base_http_test.py b/frigate/test/http_api/base_http_test.py index ad1d449c5b..e7a1d03e87 100644 --- a/frigate/test/http_api/base_http_test.py +++ b/frigate/test/http_api/base_http_test.py @@ -10,7 +10,7 @@ from frigate.api.fastapi_app import create_fastapi_app from frigate.config import FrigateConfig from frigate.models import Event, Recordings, ReviewSegment -from frigate.review.maintainer import SeverityEnum +from frigate.review.types import SeverityEnum from frigate.test.const import TEST_DB, TEST_DB_CLEANUPS diff --git a/frigate/test/http_api/test_http_review.py b/frigate/test/http_api/test_http_review.py index 352b79c7a5..11bd33495c 100644 --- a/frigate/test/http_api/test_http_review.py +++ b/frigate/test/http_api/test_http_review.py @@ -3,7 +3,7 @@ from fastapi.testclient import TestClient from frigate.models import Event, Recordings, ReviewSegment -from frigate.review.maintainer import SeverityEnum +from frigate.review.types import SeverityEnum from frigate.test.http_api.base_http_test import BaseTestHttp diff --git a/frigate/track/tracked_object.py b/frigate/track/tracked_object.py index 65e7a2ed5a..3280965da3 100644 --- a/frigate/track/tracked_object.py +++ b/frigate/track/tracked_object.py @@ -13,6 +13,7 @@ CameraConfig, ModelConfig, ) +from frigate.review.types import SeverityEnum from frigate.util.image import ( area, calculate_region, @@ -59,6 +60,27 @@ def __init__( self.pending_loitering = False self.previous = self.to_dict() + @property + def max_severity(self) -> Optional[str]: + review_config = self.camera_config.review + + if self.obj_data["label"] in review_config.alerts.labels and ( + not review_config.alerts.required_zones + or set(self.entered_zones) & set(review_config.alerts.required_zones) + ): + return SeverityEnum.alert + + if ( + not review_config.detections.labels + or self.obj_data["label"] in review_config.detections.labels + ) and ( + not review_config.detections.required_zones + or set(self.entered_zones) & set(review_config.detections.required_zones) + ): + return SeverityEnum.detection + + return None + def _is_false_positive(self): # once a true positive, always a true positive if not self.false_positive: @@ -232,6 +254,7 @@ def to_dict(self, include_thumbnail: bool = False): "attributes": self.attributes, "current_attributes": self.obj_data["attributes"], "pending_loitering": self.pending_loitering, + "max_severity": self.max_severity, } if include_thumbnail: From 6b12a45a958b6eb2175d4071156d9039399c8d7a Mon Sep 17 00:00:00 2001 From: Blake Blackshear Date: Tue, 10 Dec 2024 07:42:55 -0600 Subject: [PATCH 02/19] return 401 for login failures (#15432) * return 401 for login failures * only setup the rate limiter when configured --- frigate/api/auth.py | 4 ++-- frigate/api/fastapi_app.py | 6 +++++- web/src/api/index.tsx | 7 +++++-- web/src/components/auth/AuthForm.tsx | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/frigate/api/auth.py b/frigate/api/auth.py index 8f0fead853..be59174504 100644 --- a/frigate/api/auth.py +++ b/frigate/api/auth.py @@ -329,7 +329,7 @@ def login(request: Request, body: AppPostLoginBody): try: db_user: User = User.get_by_id(user) except DoesNotExist: - return JSONResponse(content={"message": "Login failed"}, status_code=400) + return JSONResponse(content={"message": "Login failed"}, status_code=401) password_hash = db_user.password_hash if verify_password(password, password_hash): @@ -340,7 +340,7 @@ def login(request: Request, body: AppPostLoginBody): response, JWT_COOKIE_NAME, encoded_jwt, expiration, JWT_COOKIE_SECURE ) return response - return JSONResponse(content={"message": "Login failed"}, status_code=400) + return JSONResponse(content={"message": "Login failed"}, status_code=401) @router.get("/users") diff --git a/frigate/api/fastapi_app.py b/frigate/api/fastapi_app.py index e3542458ef..168404ea61 100644 --- a/frigate/api/fastapi_app.py +++ b/frigate/api/fastapi_app.py @@ -87,7 +87,11 @@ async def startup(): logger.info("FastAPI started") # Rate limiter (used for login endpoint) - auth.rateLimiter.set_limit(frigate_config.auth.failed_login_rate_limit or "") + if frigate_config.auth.failed_login_rate_limit is None: + limiter.enabled = False + else: + auth.rateLimiter.set_limit(frigate_config.auth.failed_login_rate_limit) + app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) app.add_middleware(SlowAPIMiddleware) diff --git a/web/src/api/index.tsx b/web/src/api/index.tsx index 3ac8806c72..a9044a6d7f 100644 --- a/web/src/api/index.tsx +++ b/web/src/api/index.tsx @@ -29,8 +29,11 @@ export function ApiProvider({ children, options }: ApiProviderType) { error.response && [401, 302, 307].includes(error.response.status) ) { - window.location.href = - error.response.headers.get("location") ?? "login"; + // redirect to the login page if not already there + const loginPage = error.response.headers.get("location") ?? "login"; + if (window.location.href !== loginPage) { + window.location.href = loginPage; + } } }, ...options, diff --git a/web/src/components/auth/AuthForm.tsx b/web/src/components/auth/AuthForm.tsx index 9daa929662..99ce37283d 100644 --- a/web/src/components/auth/AuthForm.tsx +++ b/web/src/components/auth/AuthForm.tsx @@ -63,7 +63,7 @@ export function UserAuthForm({ className, ...props }: UserAuthFormProps) { toast.error("Exceeded rate limit. Try again later.", { position: "top-center", }); - } else if (err.response?.status === 400) { + } else if (err.response?.status === 401) { toast.error("Login failed", { position: "top-center", }); From 0e3fb6cbddd3bafc1135b3d298bf5514c309299f Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Wed, 11 Dec 2024 18:46:42 -0600 Subject: [PATCH 03/19] Standardize handling of config files (#15451) * Standardize handling of config files * Formatting * Remove unused --- frigate/api/app.py | 26 ++++---------------------- frigate/config/config.py | 9 +++------ frigate/detectors/plugins/rknn.py | 6 +++--- frigate/ptz/autotrack.py | 11 ++--------- frigate/util/config.py | 10 ++++++++++ 5 files changed, 22 insertions(+), 40 deletions(-) diff --git a/frigate/api/app.py b/frigate/api/app.py index 53855efcac..a94c6415ca 100644 --- a/frigate/api/app.py +++ b/frigate/api/app.py @@ -21,13 +21,13 @@ from frigate.api.defs.request.app_body import AppConfigSetBody from frigate.api.defs.tags import Tags from frigate.config import FrigateConfig -from frigate.const import CONFIG_DIR from frigate.models import Event, Timeline from frigate.util.builtin import ( clean_camera_user_pass, get_tz_modifiers, update_yaml_from_url, ) +from frigate.util.config import find_config_file from frigate.util.services import ( ffprobe_stream, get_nvidia_driver_info, @@ -147,13 +147,7 @@ def config(request: Request): @router.get("/config/raw") def config_raw(): - config_file = os.environ.get("CONFIG_FILE", "/config/config.yml") - - # Check if we can use .yaml instead of .yml - config_file_yaml = config_file.replace(".yml", ".yaml") - - if os.path.isfile(config_file_yaml): - config_file = config_file_yaml + config_file = find_config_file() if not os.path.isfile(config_file): return JSONResponse( @@ -198,13 +192,7 @@ def config_save(save_option: str, body: Any = Body(media_type="text/plain")): # Save the config to file try: - config_file = os.environ.get("CONFIG_FILE", "/config/config.yml") - - # Check if we can use .yaml instead of .yml - config_file_yaml = config_file.replace(".yml", ".yaml") - - if os.path.isfile(config_file_yaml): - config_file = config_file_yaml + config_file = find_config_file() with open(config_file, "w") as f: f.write(new_config) @@ -253,13 +241,7 @@ def config_save(save_option: str, body: Any = Body(media_type="text/plain")): @router.put("/config/set") def config_set(request: Request, body: AppConfigSetBody): - config_file = os.environ.get("CONFIG_FILE", f"{CONFIG_DIR}/config.yml") - - # Check if we can use .yaml instead of .yml - config_file_yaml = config_file.replace(".yml", ".yaml") - - if os.path.isfile(config_file_yaml): - config_file = config_file_yaml + config_file = find_config_file() with open(config_file, "r") as f: old_raw_config = f.read() diff --git a/frigate/config/config.py b/frigate/config/config.py index 8c0b52e92f..770588b932 100644 --- a/frigate/config/config.py +++ b/frigate/config/config.py @@ -29,6 +29,7 @@ ) from frigate.util.config import ( StreamInfoRetriever, + find_config_file, get_relative_coordinates, migrate_frigate_config, ) @@ -67,7 +68,6 @@ yaml = YAML() -DEFAULT_CONFIG_FILE = "/config/config.yml" DEFAULT_CONFIG = """ mqtt: enabled: False @@ -638,16 +638,13 @@ def ensure_zones_and_cameras_have_different_names(cls, v: Dict[str, CameraConfig @classmethod def load(cls, **kwargs): - config_path = os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE) - - if not os.path.isfile(config_path): - config_path = config_path.replace("yml", "yaml") + config_path = find_config_file() # No configuration file found, create one. new_config = False if not os.path.isfile(config_path): logger.info("No config file found, saving default config") - config_path = DEFAULT_CONFIG_FILE + config_path = config_path new_config = True else: # Check if the config file needs to be migrated. diff --git a/frigate/detectors/plugins/rknn.py b/frigate/detectors/plugins/rknn.py index dae5cc0576..df94d7b623 100644 --- a/frigate/detectors/plugins/rknn.py +++ b/frigate/detectors/plugins/rknn.py @@ -136,17 +136,17 @@ def download_model(self, filename): def check_config(self, config): if (config.model.width != 320) or (config.model.height != 320): raise Exception( - "Make sure to set the model width and height to 320 in your config.yml." + "Make sure to set the model width and height to 320 in your config." ) if config.model.input_pixel_format != "bgr": raise Exception( - 'Make sure to set the model input_pixel_format to "bgr" in your config.yml.' + 'Make sure to set the model input_pixel_format to "bgr" in your config.' ) if config.model.input_tensor != "nhwc": raise Exception( - 'Make sure to set the model input_tensor to "nhwc" in your config.yml.' + 'Make sure to set the model input_tensor to "nhwc" in your config.' ) def detect_raw(self, tensor_input): diff --git a/frigate/ptz/autotrack.py b/frigate/ptz/autotrack.py index 03bb3840e3..9f7f5f1b81 100644 --- a/frigate/ptz/autotrack.py +++ b/frigate/ptz/autotrack.py @@ -2,7 +2,6 @@ import copy import logging -import os import queue import threading import time @@ -29,11 +28,11 @@ AUTOTRACKING_ZOOM_EDGE_THRESHOLD, AUTOTRACKING_ZOOM_IN_HYSTERESIS, AUTOTRACKING_ZOOM_OUT_HYSTERESIS, - CONFIG_DIR, ) from frigate.ptz.onvif import OnvifController from frigate.track.tracked_object import TrackedObject from frigate.util.builtin import update_yaml_file +from frigate.util.config import find_config_file from frigate.util.image import SharedMemoryFrameManager, intersection_over_union logger = logging.getLogger(__name__) @@ -328,13 +327,7 @@ def _autotracker_setup(self, camera_config: CameraConfig, camera: str): self.autotracker_init[camera] = True def _write_config(self, camera): - config_file = os.environ.get("CONFIG_FILE", f"{CONFIG_DIR}/config.yml") - - # Check if we can use .yaml instead of .yml - config_file_yaml = config_file.replace(".yml", ".yaml") - - if os.path.isfile(config_file_yaml): - config_file = config_file_yaml + config_file = find_config_file() logger.debug( f"{camera}: Writing new config with autotracker motion coefficients: {self.config.cameras[camera].onvif.autotracking.movement_weights}" diff --git a/frigate/util/config.py b/frigate/util/config.py index 3f3c45aa6b..6bdbc04306 100644 --- a/frigate/util/config.py +++ b/frigate/util/config.py @@ -14,6 +14,16 @@ logger = logging.getLogger(__name__) CURRENT_CONFIG_VERSION = "0.15-0" +DEFAULT_CONFIG_FILE = "/config/config.yml" + + +def find_config_file() -> str: + config_path = os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE) + + if not os.path.isfile(config_path): + config_path = config_path.replace("yml", "yaml") + + return config_path def migrate_frigate_config(config_file: str): From 53b96dfb897fba2e3453c5d5b5fbc0a122a2efbf Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Wed, 11 Dec 2024 20:19:08 -0600 Subject: [PATCH 04/19] Improve semantic search docs (#15453) --- docs/docs/configuration/semantic_search.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/docs/configuration/semantic_search.md b/docs/docs/configuration/semantic_search.md index 7b0a0bc912..ab3937c53c 100644 --- a/docs/docs/configuration/semantic_search.md +++ b/docs/docs/configuration/semantic_search.md @@ -5,7 +5,7 @@ title: Using Semantic Search Semantic Search in Frigate allows you to find tracked objects within your review items using either the image itself, a user-defined text description, or an automatically generated one. This feature works by creating _embeddings_ — numerical vector representations — for both the images and text descriptions of your tracked objects. By comparing these embeddings, Frigate assesses their similarities to deliver relevant search results. -Frigate has support for [Jina AI's CLIP model](https://huggingface.co/jinaai/jina-clip-v1) to create embeddings, which runs locally. Embeddings are then saved to Frigate's database. +Frigate uses [Jina AI's CLIP model](https://huggingface.co/jinaai/jina-clip-v1) to create and save embeddings to Frigate's database. All of this runs locally. Semantic Search is accessed via the _Explore_ view in the Frigate UI. @@ -19,7 +19,7 @@ For best performance, 16GB or more of RAM and a dedicated GPU are recommended. ## Configuration -Semantic Search is disabled by default, and must be enabled in your config file before it can be used. Semantic Search is a global configuration setting. +Semantic Search is disabled by default, and must be enabled in your config file or in the UI's Settings page before it can be used. Semantic Search is a global configuration setting. ```yaml semantic_search: @@ -29,9 +29,9 @@ semantic_search: :::tip -The embeddings database can be re-indexed from the existing tracked objects in your database by adding `reindex: True` to your `semantic_search` configuration. Depending on the number of tracked objects you have, it can take a long while to complete and may max out your CPU while indexing. Make sure to set the config back to `False` before restarting Frigate again. +The embeddings database can be re-indexed from the existing tracked objects in your database by adding `reindex: True` to your `semantic_search` configuration or by toggling the switch on the Search Settings page in the UI and restarting Frigate. Depending on the number of tracked objects you have, it can take a long while to complete and may max out your CPU while indexing. Make sure to turn the UI's switch off or set the config back to `False` before restarting Frigate again. -If you are enabling the Search feature for the first time, be advised that Frigate does not automatically index older tracked objects. You will need to enable the `reindex` feature in order to do that. +If you are enabling Semantic Search for the first time, be advised that Frigate does not automatically index older tracked objects. You will need to enable the `reindex` feature in order to do that. ::: @@ -39,9 +39,9 @@ If you are enabling the Search feature for the first time, be advised that Friga The vision model is able to embed both images and text into the same vector space, which allows `image -> image` and `text -> image` similarity searches. Frigate uses this model on tracked objects to encode the thumbnail image and store it in the database. When searching for tracked objects via text in the search box, Frigate will perform a `text -> image` similarity search against this embedding. When clicking "Find Similar" in the tracked object detail pane, Frigate will perform an `image -> image` similarity search to retrieve the closest matching thumbnails. -The text model is used to embed tracked object descriptions and perform searches against them. Descriptions can be created, viewed, and modified on the Search page when clicking on the gray tracked object chip at the top left of each review item. See [the Generative AI docs](/configuration/genai.md) for more information on how to automatically generate tracked object descriptions. +The text model is used to embed tracked object descriptions and perform searches against them. Descriptions can be created, viewed, and modified on the Explore page when clicking on thumbnail of a tracked object. See [the Generative AI docs](/configuration/genai.md) for more information on how to automatically generate tracked object descriptions. -Differently weighted CLIP models are available and can be selected by setting the `model_size` config option as `small` or `large`: +Differently weighted versions of the Jina model are available and can be selected by setting the `model_size` config option as `small` or `large`: ```yaml semantic_search: @@ -50,7 +50,7 @@ semantic_search: ``` - Configuring the `large` model employs the full Jina model and will automatically run on the GPU if applicable. -- Configuring the `small` model employs a quantized version of the model that uses less RAM and runs on CPU with a very negligible difference in embedding quality. +- Configuring the `small` model employs a quantized version of the Jina model that uses less RAM and runs on CPU with a very negligible difference in embedding quality. ### GPU Acceleration @@ -84,7 +84,7 @@ If the correct build is used for your GPU and the `large` model is configured, t ## Usage and Best Practices -1. Semantic Search is used in conjunction with the other filters available on the Search page. Use a combination of traditional filtering and Semantic Search for the best results. +1. Semantic Search is used in conjunction with the other filters available on the Explore page. Use a combination of traditional filtering and Semantic Search for the best results. 2. Use the thumbnail search type when searching for particular objects in the scene. Use the description search type when attempting to discern the intent of your object. 3. Because of how the AI models Frigate uses have been trained, the comparison between text and image embedding distances generally means that with multi-modal (`thumbnail` and `description`) searches, results matching `description` will appear first, even if a `thumbnail` embedding may be a better match. Play with the "Search Type" setting to help find what you are looking for. Note that if you are generating descriptions for specific objects or zones only, this may cause search results to prioritize the objects with descriptions even if the the ones without them are more relevant. 4. Make your search language and tone closely match exactly what you're looking for. If you are using thumbnail search, **phrase your query as an image caption**. Searching for "red car" may not work as well as "red sedan driving down a residential street on a sunny day". From b4d82084a98cc245e73a1be922270994275ce128 Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Thu, 12 Dec 2024 08:22:30 -0600 Subject: [PATCH 05/19] Fixes (#15465) * Fix single event return * Allow customizing if search is preserved for overlay state * Remove timeout * Cleanup * Cleanup naming --- frigate/events/cleanup.py | 5 +++-- web/src/hooks/use-overlay-state.tsx | 3 ++- web/src/pages/Events.tsx | 7 +++++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/frigate/events/cleanup.py b/frigate/events/cleanup.py index b1b485c3d2..741f0884cd 100644 --- a/frigate/events/cleanup.py +++ b/frigate/events/cleanup.py @@ -256,8 +256,9 @@ def expire_clips(self) -> list[str]: events_to_update = [] - for batch in query.iterator(): - events_to_update.extend([event.id for event in batch]) + for event in query.iterator(): + events_to_update.append(event) + if len(events_to_update) >= CHUNK_SIZE: logger.debug( f"Updating {update_params} for {len(events_to_update)} events" diff --git a/web/src/hooks/use-overlay-state.tsx b/web/src/hooks/use-overlay-state.tsx index 841585b25d..7a43383d47 100644 --- a/web/src/hooks/use-overlay-state.tsx +++ b/web/src/hooks/use-overlay-state.tsx @@ -5,6 +5,7 @@ import { usePersistence } from "./use-persistence"; export function useOverlayState( key: string, defaultValue: S | undefined = undefined, + preserveSearch: boolean = true, ): [S | undefined, (value: S, replace?: boolean) => void] { const location = useLocation(); const navigate = useNavigate(); @@ -15,7 +16,7 @@ export function useOverlayState( (value: S, replace: boolean = false) => { const newLocationState = { ...currentLocationState }; newLocationState[key] = value; - navigate(location.pathname + location.search, { + navigate(location.pathname + (preserveSearch ? location.search : ""), { state: newLocationState, replace, }); diff --git a/web/src/pages/Events.tsx b/web/src/pages/Events.tsx index 8c6f3cd381..28625bbd83 100644 --- a/web/src/pages/Events.tsx +++ b/web/src/pages/Events.tsx @@ -39,8 +39,11 @@ export default function Events() { const [showReviewed, setShowReviewed] = usePersistence("showReviewed", false); - const [recording, setRecording] = - useOverlayState("recording"); + const [recording, setRecording] = useOverlayState( + "recording", + undefined, + false, + ); useSearchEffect("id", (reviewId: string) => { axios From ed2e1f3f72315b3cbbaa6a24c2b6f12d8b918ccd Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Thu, 12 Dec 2024 08:46:06 -0600 Subject: [PATCH 06/19] Remove debug cleanup change (#15468) --- frigate/events/cleanup.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/frigate/events/cleanup.py b/frigate/events/cleanup.py index 741f0884cd..713e336301 100644 --- a/frigate/events/cleanup.py +++ b/frigate/events/cleanup.py @@ -331,9 +331,8 @@ def expire_clips(self) -> list[str]: def run(self) -> None: # only expire events every 5 minutes - while not self.stop_event.wait(1): + while not self.stop_event.wait(300): events_with_expired_clips = self.expire_clips() - return # delete timeline entries for events that have expired recordings # delete up to 100,000 at a time From d302b6e1988c2e5bd333b1efc3dad1ce38b48f73 Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Thu, 12 Dec 2024 14:46:00 -0600 Subject: [PATCH 07/19] Cap storage bandwidth (#15473) --- frigate/storage.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/frigate/storage.py b/frigate/storage.py index 2dbd07a510..1c4650271c 100644 --- a/frigate/storage.py +++ b/frigate/storage.py @@ -17,6 +17,8 @@ Recordings.end_time - Recordings.start_time ) +MAX_CALCULATED_BANDWIDTH = 10000 # 10Gb/hr + class StorageMaintainer(threading.Thread): """Maintain frigates recording storage.""" @@ -52,6 +54,12 @@ def calculate_camera_bandwidth(self) -> None: * 3600, 2, ) + + if bandwidth > MAX_CALCULATED_BANDWIDTH: + logger.warning( + f"{camera} has a bandwidth of {bandwidth} MB/hr which exceeds the expected maximum. This typically indicates an issue with the cameras recordings." + ) + bandwidth = MAX_CALCULATED_BANDWIDTH except TypeError: bandwidth = 0 From f336a91fee407022694a59eecc947ada2f4f5cb4 Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Thu, 12 Dec 2024 21:22:47 -0600 Subject: [PATCH 08/19] Cleanup handling of first object message (#15480) --- frigate/events/maintainer.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/frigate/events/maintainer.py b/frigate/events/maintainer.py index e2b9245d6e..68e7432abd 100644 --- a/frigate/events/maintainer.py +++ b/frigate/events/maintainer.py @@ -82,18 +82,23 @@ def run(self) -> None: ) if source_type == EventTypeEnum.tracked_object: + id = event_data["id"] self.timeline_queue.put( ( camera, source_type, event_type, - self.events_in_process.get(event_data["id"]), + self.events_in_process.get(id), event_data, ) ) - if event_type == EventStateEnum.start: - self.events_in_process[event_data["id"]] = event_data + # if this is the first message, just store it and continue, its not time to insert it in the db + if ( + event_type == EventStateEnum.start + or id not in self.events_in_process + ): + self.events_in_process[id] = event_data continue self.handle_object_detection(event_type, camera, event_data) @@ -123,10 +128,6 @@ def handle_object_detection( """handle tracked object event updates.""" updated_db = False - # if this is the first message, just store it and continue, its not time to insert it in the db - if event_type == EventStateEnum.start: - self.events_in_process[event_data["id"]] = event_data - if should_update_db(self.events_in_process[event_data["id"]], event_data): updated_db = True camera_config = self.config.cameras[camera] From 869fa2631ef765b761ea9f8d39c643869d82c755 Mon Sep 17 00:00:00 2001 From: Blake Blackshear Date: Fri, 13 Dec 2024 07:34:09 -0600 Subject: [PATCH 09/19] apply zizmor recommendations (#15490) --- .github/workflows/ci.yml | 16 ++++++++++++- .github/workflows/dependabot-auto-merge.yaml | 24 -------------------- .github/workflows/pull_request.yml | 12 +++++++++- .github/workflows/release.yml | 9 ++++++-- .github/workflows/stale.yml | 5 ++-- 5 files changed, 36 insertions(+), 30 deletions(-) delete mode 100644 .github/workflows/dependabot-auto-merge.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b06f0dc8f..996b1e8e75 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ on: - dev - master paths-ignore: - - 'docs/**' + - "docs/**" # only run the latest commit to avoid cache overwrites concurrency: @@ -24,6 +24,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup @@ -45,6 +47,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup @@ -86,6 +90,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup @@ -112,6 +118,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup @@ -140,6 +148,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup @@ -165,6 +175,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup @@ -188,6 +200,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up QEMU and Buildx id: setup uses: ./.github/actions/setup diff --git a/.github/workflows/dependabot-auto-merge.yaml b/.github/workflows/dependabot-auto-merge.yaml deleted file mode 100644 index 1c047c346b..0000000000 --- a/.github/workflows/dependabot-auto-merge.yaml +++ /dev/null @@ -1,24 +0,0 @@ -name: dependabot-auto-merge -on: pull_request - -permissions: - contents: write - -jobs: - dependabot-auto-merge: - runs-on: ubuntu-latest - if: github.actor == 'dependabot[bot]' - steps: - - name: Get Dependabot metadata - id: metadata - uses: dependabot/fetch-metadata@v2 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - - name: Enable auto-merge for Dependabot PRs - if: steps.metadata.outputs.dependency-type == 'direct:development' && (steps.metadata.outputs.update-type == 'version-update:semver-minor' || steps.metadata.outputs.update-type == 'version-update:semver-patch') - run: | - gh pr review --approve "$PR_URL" - gh pr merge --auto --squash "$PR_URL" - env: - PR_URL: ${{ github.event.pull_request.html_url }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index bce97a07e9..39c76e3503 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -3,7 +3,7 @@ name: On pull request on: pull_request: paths-ignore: - - 'docs/**' + - "docs/**" env: DEFAULT_PYTHON: 3.9 @@ -19,6 +19,8 @@ jobs: DOCKER_BUILDKIT: "1" steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: actions/setup-node@master with: node-version: 16.x @@ -38,6 +40,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: actions/setup-node@master with: node-version: 16.x @@ -52,6 +56,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: actions/setup-node@master with: node-version: 20.x @@ -67,6 +73,8 @@ jobs: steps: - name: Check out the repository uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up Python ${{ env.DEFAULT_PYTHON }} uses: actions/setup-python@v5.1.0 with: @@ -88,6 +96,8 @@ jobs: steps: - name: Check out code uses: actions/checkout@v4 + with: + persist-credentials: false - uses: actions/setup-node@master with: node-version: 16.x diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6e90b9c784..ace4c3b3f4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,6 +11,8 @@ jobs: steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - id: lowercaseRepo uses: ASzc/change-string-case-action@v6 with: @@ -22,10 +24,13 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Create tag variables + env: + TAG: ${{ github.ref_name }} + LOWERCASE_REPO: ${{ steps.lowercaseRepo.outputs.lowercase }} run: | - BUILD_TYPE=$([[ "${{ github.ref_name }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && echo "stable" || echo "beta") + BUILD_TYPE=$([[ "${TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && echo "stable" || echo "beta") echo "BUILD_TYPE=${BUILD_TYPE}" >> $GITHUB_ENV - echo "BASE=ghcr.io/${{ steps.lowercaseRepo.outputs.lowercase }}" >> $GITHUB_ENV + echo "BASE=ghcr.io/${LOWERCASE_REPO}" >> $GITHUB_ENV echo "BUILD_TAG=${GITHUB_SHA::7}" >> $GITHUB_ENV echo "CLEAN_VERSION=$(echo ${GITHUB_REF##*/} | tr '[:upper:]' '[:lower:]' | sed 's/^[v]//')" >> $GITHUB_ENV - name: Tag and push the main image diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 8e7e3223cb..011f70afd3 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -23,7 +23,9 @@ jobs: exempt-pr-labels: "pinned,security,dependencies" operations-per-run: 120 - name: Print outputs - run: echo ${{ join(steps.stale.outputs.*, ',') }} + env: + STALE_OUTPUT: ${{ join(steps.stale.outputs.*, ',') }} + run: echo "$STALE_OUTPUT" # clean_ghcr: # name: Delete outdated dev container images @@ -38,4 +40,3 @@ jobs: # account-type: personal # token: ${{ secrets.GITHUB_TOKEN }} # token-type: github-token - From 1ea282fba88960524ff1847197a9fb34a2dc5908 Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Fri, 13 Dec 2024 13:02:41 -0600 Subject: [PATCH 10/19] Improve the message for missing objects in review items (#15500) --- .../overlay/detail/ReviewDetailDialog.tsx | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/web/src/components/overlay/detail/ReviewDetailDialog.tsx b/web/src/components/overlay/detail/ReviewDetailDialog.tsx index c3e7ac91dd..d3c8864b77 100644 --- a/web/src/components/overlay/detail/ReviewDetailDialog.tsx +++ b/web/src/components/overlay/detail/ReviewDetailDialog.tsx @@ -74,6 +74,23 @@ export default function ReviewDetailDialog({ return events.length != review?.data.detections.length; }, [review, events]); + const missingObjects = useMemo(() => { + if (!review || !events) { + return []; + } + + const detectedIds = review.data.detections; + const missing = Array.from( + new Set( + events + .filter((event) => !detectedIds.includes(event.id)) + .map((event) => event.label), + ), + ); + + return missing; + }, [review, events]); + const formattedDate = useFormattedTimestamp( review?.start_time ?? 0, config?.ui.time_format == "24hour" @@ -263,8 +280,13 @@ export default function ReviewDetailDialog({ {hasMismatch && (
- Some objects that were detected are not included in this list - because the object does not have a snapshot + Some objects may have been detected in this review item that + did not qualify as an alert or detection. Adjust your + configuration if you want Frigate to save tracked objects for + any missing labels. + {missingObjects.length > 0 && ( +
{missingObjects.join(", ")}
+ )}
)}
From 0763f560478949953b400260b6c471ddf88ecccb Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Fri, 13 Dec 2024 13:52:56 -0600 Subject: [PATCH 11/19] Update iframe interval recommendation (#15501) * Update iframe interval recommendation * clarify * tweaks * wording --- docs/docs/configuration/live.md | 2 +- docs/docs/frigate/camera_setup.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/configuration/live.md b/docs/docs/configuration/live.md index 31e720031d..25bf7537c0 100644 --- a/docs/docs/configuration/live.md +++ b/docs/docs/configuration/live.md @@ -23,7 +23,7 @@ If you are using go2rtc, you should adjust the following settings in your camera - Video codec: **H.264** - provides the most compatible video codec with all Live view technologies and browsers. Avoid any kind of "smart codec" or "+" codec like _H.264+_ or _H.265+_. as these non-standard codecs remove keyframes (see below). - Audio codec: **AAC** - provides the most compatible audio codec with all Live view technologies and browsers that support audio. -- I-frame interval (sometimes called the keyframe interval, the interframe space, or the GOP length): match your camera's frame rate, or choose "1x" (for interframe space on Reolink cameras). For example, if your stream outputs 20fps, your i-frame interval should be 20 (or 1x on Reolink). Values higher than the frame rate will cause the stream to take longer to begin playback. See [this page](https://gardinal.net/understanding-the-keyframe-interval/) for more on keyframes. +- I-frame interval (sometimes called the keyframe interval, the interframe space, or the GOP length): match your camera's frame rate, or choose "1x" (for interframe space on Reolink cameras). For example, if your stream outputs 20fps, your i-frame interval should be 20 (or 1x on Reolink). Values higher than the frame rate will cause the stream to take longer to begin playback. See [this page](https://gardinal.net/understanding-the-keyframe-interval/) for more on keyframes. For many users this may not be an issue, but it should be noted that that a 1x i-frame interval will cause more storage utilization if you are using the stream for the `record` role as well. The default video and audio codec on your camera may not always be compatible with your browser, which is why setting them to H.264 and AAC is recommended. See the [go2rtc docs](https://github.com/AlexxIT/go2rtc?tab=readme-ov-file#codecs-madness) for codec support information. diff --git a/docs/docs/frigate/camera_setup.md b/docs/docs/frigate/camera_setup.md index 33ae24cabd..421046dd7c 100644 --- a/docs/docs/frigate/camera_setup.md +++ b/docs/docs/frigate/camera_setup.md @@ -28,7 +28,7 @@ For the Dahua/Loryta 5442 camera, I use the following settings: - Encode Mode: H.264 - Resolution: 2688\*1520 - Frame Rate(FPS): 15 -- I Frame Interval: 30 +- I Frame Interval: 30 (15 can also be used to prioritize streaming performance - see the [camera settings recommendations](../configuration/live) for more info) **Sub Stream (Detection)** From 1b7fe9523df83d6ade94903e132233cc80abf31c Mon Sep 17 00:00:00 2001 From: FL42 <46161216+fl42@users.noreply.github.com> Date: Sat, 14 Dec 2024 15:54:13 +0100 Subject: [PATCH 12/19] fix: use requests.Session() for DeepStack API (#15505) --- frigate/detectors/plugins/deepstack.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frigate/detectors/plugins/deepstack.py b/frigate/detectors/plugins/deepstack.py index 20d37fa8e9..e00a4e70d2 100644 --- a/frigate/detectors/plugins/deepstack.py +++ b/frigate/detectors/plugins/deepstack.py @@ -32,6 +32,7 @@ def __init__(self, detector_config: DeepstackDetectorConfig): self.api_timeout = detector_config.api_timeout self.api_key = detector_config.api_key self.labels = detector_config.model.merged_labelmap + self.session = requests.Session() def get_label_index(self, label_value): if label_value.lower() == "truck": @@ -51,7 +52,7 @@ def detect_raw(self, tensor_input): data = {"api_key": self.api_key} try: - response = requests.post( + response = self.session.post( self.api_url, data=data, files={"image": image_bytes}, From 17f8939f9783f67a0f29ee861a299c78573eea0d Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Sat, 14 Dec 2024 13:58:39 -0600 Subject: [PATCH 13/19] Add FAQ to explain why streams might work in VLC but not in Frigate (#15513) * Add faq to explain why streams might work in VLC but not in Frigate * fix go2rtc version number * wording * mention udp input args and preset --- docs/docs/configuration/advanced.md | 2 +- docs/docs/troubleshooting/faqs.md | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/docs/configuration/advanced.md b/docs/docs/configuration/advanced.md index da53838861..4007154b10 100644 --- a/docs/docs/configuration/advanced.md +++ b/docs/docs/configuration/advanced.md @@ -174,7 +174,7 @@ NOTE: The folder that is set for the config needs to be the folder that contains ### Custom go2rtc version -Frigate currently includes go2rtc v1.9.4, there may be certain cases where you want to run a different version of go2rtc. +Frigate currently includes go2rtc v1.9.2, there may be certain cases where you want to run a different version of go2rtc. To do this: diff --git a/docs/docs/troubleshooting/faqs.md b/docs/docs/troubleshooting/faqs.md index 7356fececf..889db33706 100644 --- a/docs/docs/troubleshooting/faqs.md +++ b/docs/docs/troubleshooting/faqs.md @@ -98,3 +98,11 @@ docker run -d \ -p 8555:8555/udp \ ghcr.io/blakeblackshear/frigate:stable ``` + +### My RTSP stream works fine in VLC, but it does not work when I put the same URL in my Frigate config. Is this a bug? + +No. Frigate uses the TCP protocol to connect to your camera's RTSP URL. VLC automatically switches between UDP and TCP depending on network conditions and stream availability. So a stream that works in VLC but not in Frigate is likely due to VLC selecting UDP as the transfer protocol. + +TCP ensures that all data packets arrive in the correct order. This is crucial for video recording, decoding, and stream processing, which is why Frigate enforces a TCP connection. UDP is faster but less reliable, as it does not guarantee packet delivery or order, and VLC does not have the same requirements as Frigate. + +You can still configure Frigate to use UDP by using ffmpeg input args or the preset `preset-rtsp-udp`. See the [ffmpeg presets](/configuration/ffmpeg_presets) documentation. From 33ee32865f2ba5de3dded425b2caa6a2753124f9 Mon Sep 17 00:00:00 2001 From: Nicolas Mowen Date: Sun, 15 Dec 2024 16:56:24 -0600 Subject: [PATCH 14/19] Ensure that go2rtc streams are cleaned (#15524) * Ensure that go2rtc streams are cleaned * Formatting * Handle go2rtc config correctly * Set type --- frigate/api/app.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/frigate/api/app.py b/frigate/api/app.py index a94c6415ca..57efdeb15c 100644 --- a/frigate/api/app.py +++ b/frigate/api/app.py @@ -134,9 +134,25 @@ def config(request: Request): for zone_name, zone in config_obj.cameras[camera_name].zones.items(): camera_dict["zones"][zone_name]["color"] = zone.color + # remove go2rtc stream passwords + go2rtc: dict[str, any] = config_obj.go2rtc.model_dump( + mode="json", warnings="none", exclude_none=True + ) + for stream_name, stream in go2rtc.get("streams", {}).items(): + if isinstance(stream, str): + cleaned = clean_camera_user_pass(stream) + else: + cleaned = [] + + for item in stream: + cleaned.append(clean_camera_user_pass(item)) + + config["go2rtc"]["streams"][stream_name] = cleaned + config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()} config["model"]["colormap"] = config_obj.model.colormap + # use merged labelamp for detector_config in config["detectors"].values(): detector_config["model"]["labelmap"] = ( request.app.frigate_config.model.merged_labelmap From d49f958d4d4dafe77718358d41cce7530ed9f217 Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Sun, 15 Dec 2024 17:03:19 -0600 Subject: [PATCH 15/19] Don't crop by region for genai snapshot for manual events (#15525) --- frigate/embeddings/maintainer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frigate/embeddings/maintainer.py b/frigate/embeddings/maintainer.py index d58a7f431d..1bc8727362 100644 --- a/frigate/embeddings/maintainer.py +++ b/frigate/embeddings/maintainer.py @@ -335,8 +335,10 @@ def handle_regenerate_description(self, event_id: str, source: str) -> None: ) # crop snapshot based on region before sending off to genai + # provide full image if region doesn't exist (manual events) + region = event.data.get("region", [0, 0, 1, 1]) height, width = img.shape[:2] - x1_rel, y1_rel, width_rel, height_rel = event.data["region"] + x1_rel, y1_rel, width_rel, height_rel = region x1, y1 = int(x1_rel * width), int(y1_rel * height) cropped_image = img[ From 717493e66821bcb26239fe81e8651ef9a64d1ca4 Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Sun, 15 Dec 2024 20:51:23 -0600 Subject: [PATCH 16/19] Improve handling of error conditions with ollama and snapshot regeneration (#15527) --- frigate/embeddings/maintainer.py | 13 +++++++++---- frigate/genai/ollama.py | 5 +++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/frigate/embeddings/maintainer.py b/frigate/embeddings/maintainer.py index 1bc8727362..2540db4f84 100644 --- a/frigate/embeddings/maintainer.py +++ b/frigate/embeddings/maintainer.py @@ -325,10 +325,15 @@ def handle_regenerate_description(self, event_id: str, source: str) -> None: ) if event.has_snapshot and source == "snapshot": - with open( - os.path.join(CLIPS_DIR, f"{event.camera}-{event.id}.jpg"), - "rb", - ) as image_file: + snapshot_file = os.path.join(CLIPS_DIR, f"{event.camera}-{event.id}.jpg") + + if not os.path.isfile(snapshot_file): + logger.error( + f"Cannot regenerate description for {event.id}, snapshot file not found: {snapshot_file}" + ) + return + + with open(snapshot_file, "rb") as image_file: snapshot_image = image_file.read() img = cv2.imdecode( np.frombuffer(snapshot_image, dtype=np.int8), cv2.IMREAD_COLOR diff --git a/frigate/genai/ollama.py b/frigate/genai/ollama.py index e61441eba5..e67d532f02 100644 --- a/frigate/genai/ollama.py +++ b/frigate/genai/ollama.py @@ -38,6 +38,11 @@ def _init_provider(self): def _send(self, prompt: str, images: list[bytes]) -> Optional[str]: """Submit a request to Ollama""" + if self.provider is None: + logger.warning( + "Ollama provider has not been initialized, a description will not be generated. Check your Ollama configuration." + ) + return None try: result = self.provider.generate( self.genai_config.model, From 292499aebc934f4e08168d82ae6d4665af44ac28 Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Mon, 16 Dec 2024 10:18:34 -0600 Subject: [PATCH 17/19] Improve review message again (#15538) --- .../overlay/detail/ReviewDetailDialog.tsx | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/web/src/components/overlay/detail/ReviewDetailDialog.tsx b/web/src/components/overlay/detail/ReviewDetailDialog.tsx index d3c8864b77..8d2f13d895 100644 --- a/web/src/components/overlay/detail/ReviewDetailDialog.tsx +++ b/web/src/components/overlay/detail/ReviewDetailDialog.tsx @@ -280,12 +280,24 @@ export default function ReviewDetailDialog({
{hasMismatch && (
- Some objects may have been detected in this review item that - did not qualify as an alert or detection. Adjust your - configuration if you want Frigate to save tracked objects for - any missing labels. + {(() => { + const detectedCount = Math.abs( + (events?.length ?? 0) - + (review?.data.detections.length ?? 0), + ); + const objectLabel = + detectedCount === 1 ? "object was" : "objects were"; + + return `${detectedCount} unavailable ${objectLabel} detected and included in this review item.`; + })()}{" "} + Those objects either did not qualify as an alert or detection + or have already been cleaned up/deleted. {missingObjects.length > 0 && ( -
{missingObjects.join(", ")}
+
+ Adjust your configuration if you want Frigate to save + tracked objects for the following labels:{" "} + {missingObjects.join(", ")} +
)}
)} From d9ef8fa20616fb5fa9df6539fc193903ce537f71 Mon Sep 17 00:00:00 2001 From: Giorgio Ughini Date: Tue, 17 Dec 2024 14:44:00 +0100 Subject: [PATCH 18/19] Fix always the same image is sent to GenAI (#15550) * Fix always the same image is sent to GenAI * Fix typo for bug where identical images are sent to GenAI * Correct formatting --- frigate/embeddings/maintainer.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/frigate/embeddings/maintainer.py b/frigate/embeddings/maintainer.py index 2540db4f84..4f81ec2d62 100644 --- a/frigate/embeddings/maintainer.py +++ b/frigate/embeddings/maintainer.py @@ -221,7 +221,10 @@ def _process_finalized(self) -> None: [snapshot_image] if event.has_snapshot and camera_config.genai.use_snapshot else ( - [thumbnail for data in self.tracked_events[event_id]] + [ + data["thumbnail"] + for data in self.tracked_events[event_id] + ] if len(self.tracked_events.get(event_id, [])) > 0 else [thumbnail] ) @@ -357,7 +360,7 @@ def handle_regenerate_description(self, event_id: str, source: str) -> None: [snapshot_image] if event.has_snapshot and source == "snapshot" else ( - [thumbnail for data in self.tracked_events[event_id]] + [data["thumbnail"] for data in self.tracked_events[event_id]] if len(self.tracked_events.get(event_id, [])) > 0 else [thumbnail] ) From 3dc26e78ef974efacea22271c3b3f074b5a977df Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Tue, 17 Dec 2024 17:33:04 -0600 Subject: [PATCH 19/19] Genai descriptions are not generated until tracked objects end (#15561) --- docs/docs/configuration/genai.md | 2 + .../overlay/detail/SearchDetailDialog.tsx | 128 +++++++++++------- 2 files changed, 81 insertions(+), 49 deletions(-) diff --git a/docs/docs/configuration/genai.md b/docs/docs/configuration/genai.md index fac44ed030..9d5f62b8ca 100644 --- a/docs/docs/configuration/genai.md +++ b/docs/docs/configuration/genai.md @@ -5,6 +5,8 @@ title: Generative AI Generative AI can be used to automatically generate descriptive text based on the thumbnails of your tracked objects. This helps with [Semantic Search](/configuration/semantic_search) in Frigate to provide more context about your tracked objects. Descriptions are accessed via the _Explore_ view in the Frigate UI by clicking on a tracked object's thumbnail. +Requests for a description are sent off automatically to your AI provider at the end of the tracked object's lifecycle. Descriptions can also be regenerated manually via the Frigate UI. + :::info Semantic Search must be enabled to use Generative AI. diff --git a/web/src/components/overlay/detail/SearchDetailDialog.tsx b/web/src/components/overlay/detail/SearchDetailDialog.tsx index b0eeac98d1..ba32eec2ba 100644 --- a/web/src/components/overlay/detail/SearchDetailDialog.tsx +++ b/web/src/components/overlay/detail/SearchDetailDialog.tsx @@ -469,60 +469,90 @@ function ObjectDetailsTab({
-
Description
-