Commit Graph

179 Commits

Author SHA1 Message Date
Josh Hawkins
580f35112e
revert changes to audio process to prevent shutdown hang (#14872) 2024-11-08 11:47:46 -07:00
Nicolas Mowen
a13b9815f6
Various fixes (#14786)
* Catch openvino error

* Remove clip deletion

* Update deletion text

* Fix timeline not respecting timezone config

* Tweaks

* More timezone fixes

* Fix

* More timezone fixes

* Fix shm docs
2024-11-04 07:07:57 -07:00
leccelecce
189d4b459f
Avoid divide by zero in shm_frame_count (#14750) 2024-11-03 08:28:19 -07:00
gtsiam
4bb420d049
Add service manager infrastructure (#14150)
* Add service manager infrastructure

The changes are (This will be a bit long):
- A ServiceManager class that spawns a background thread and deals with
  service lifecycle management. The idea is that service lifecycle code
  will run in async functions, so a single thread is enough to manage
  any (reasonable) amount of services.

- A Service class, that offers start(), stop() and restart() methods
  that simply notify the service manager to... well. Start, stop or
  restart a service.

(!) Warning: Note that this differs from mp.Process.start/stop in that
  the service commands are sent asynchronously and will complete
  "eventually". This is good because it means that business logic is
  fast when booting up and shutting down, but we need to make sure
  that code does not rely on start() and stop() being instant
  (Mainly pid assignments).

  Subclasses of the Service class should use the on_start and on_stop
  methods to monitor for service events. These will be run by the
  service manager thread, so we need to be careful not to block
  execution here. Standard async stuff.

(!) Note on service names: Service names should be unique within a
  ServiceManager. Make sure that you pass the name you want to
  super().__init__(name="...") if you plan to spawn multiple instances
  of a service.

- A ServiceProcess class: A Service that wraps a multiprocessing.Process
  into a Service. It offers a run() method subclasses can override and
  can support in-place restarting using the service manager.

And finally, I lied a bit about this whole thing using a single thread.
I can't find any way to run python multiprocessing in async, so there is
a MultiprocessingWaiter thread that waits for multiprocessing events and
notifies any pending futures. This was uhhh... fun? No, not really.
But it works. Using this part of the code just involves calling the
provided wait method. See the implementation of ServiceProcess for more
details.

Mirror util.Process hooks onto service process

Remove Service.__name attribute

Do not serialize process object on ServiceProcess start.

asd

* Update frigate dictionary

* Convert AudioProcessor to service process
2024-10-21 10:00:38 -05:00
Nicolas Mowen
dd6276e706
Embeddings fixes (#14269)
* Add debugging logs for more info

* Improve timeout handling

* Fix event cleanup

* Handle zmq error and empty data

* Don't run download

* Remove unneeded embeddings creations

* Update timouts

* Init models immediately

* Fix order of init

* Cleanup
2024-10-10 16:37:43 -05:00
Nicolas Mowen
8ade85edec
Restructure embeddings (#14266)
* Restructure embeddings

* Use ZMQ to proxy embeddings requests

* Handle serialization

* Formatting

* Remove unused
2024-10-10 09:42:24 -06:00
Nicolas Mowen
a2ca18a714
Bug fixes (#14263)
* Simplify loitering logic

* Fix divide by zero

* Add device config for semantic search

* Add docs
2024-10-10 07:09:12 -06:00
Josh Hawkins
24ac9f3e5a
Use sqlite-vec extension instead of chromadb for embeddings (#14163)
* swap sqlite_vec for chroma in requirements

* load sqlite_vec in embeddings manager

* remove chroma and revamp Embeddings class for sqlite_vec

* manual minilm onnx inference

* remove chroma in clip model

* migrate api from chroma to sqlite_vec

* migrate event cleanup from chroma to sqlite_vec

* migrate embedding maintainer from chroma to sqlite_vec

* genai description for sqlite_vec

* load sqlite_vec in main thread db

* extend the SqliteQueueDatabase class and use peewee db.execute_sql

* search with Event type for similarity

* fix similarity search

* install and add comment about transformers

* fix normalization

* add id filter

* clean up

* clean up

* fully remove chroma and add transformers env var

* readd uvicorn for fastapi

* readd tokenizer parallelism env var

* remove chroma from docs

* remove chroma from UI

* try removing custom pysqlite3 build

* hard code limit

* optimize queries

* revert explore query

* fix query

* keep building pysqlite3

* single pass fetch and process

* remove unnecessary re-embed

* update deps

* move SqliteVecQueueDatabase to db directory

* make search thumbnail take up full size of results box

* improve typing

* improve model downloading and add status screen

* daemon downloading thread

* catch case when semantic search is disabled

* fix typing

* build sqlite_vec from source

* resolve conflict

* file permissions

* try build deps

* remove sources

* sources

* fix thread start

* include git in build

* reorder embeddings after detectors are started

* build with sqlite amalgamation

* non-platform specific

* use wget instead of curl

* remove unzip -d

* remove sqlite_vec from requirements and load the compiled version

* fix build

* avoid race in db connection

* add scale_factor and bias to description zscore normalization
2024-10-07 14:30:45 -06:00
Nicolas Mowen
74047453ef
Bug Fixes (#14193)
* fix getting device from empty list

* Overwrite all fields

* Fix header too low
2024-10-07 07:18:09 -06:00
gtsiam
e5e196bd7f
Fix logging (#14122)
Fixes logging without introducing more junk into FrigateApp.
2024-10-03 06:33:53 -06:00
gtsiam
3c015bf822
Do not migrate db to new config path (#14123)
I just saw this, and I would be very surprised by that behaviour as a
user. Changing the db path would randomly move the database, and
changing it back (or to anything, really) would not. These kinds of
advanced settings are generally expected to do one thing: Change the
path frigate opens the database from. The end.
2024-10-02 19:34:14 -06:00
Nicolas Mowen
f36e7430ae
Fix logging (#14079)
* Fix log level setting

* fix app.py mypy issues
2024-09-30 17:45:22 -05:00
gtsiam
bbbb3b4a06
Split config.py into multiple files (#14038)
* Replace logging.warn with logging.warning

* Install config global state early

* Split config.py into more manageable pieces
2024-09-28 14:21:42 -05:00
Nicolas Mowen
05fe7f8a48
Fixes & Tweaks (#14013)
* Rework to create util for onnx initialization

* Fix shm log

* Fix onClick exceptoins
2024-09-27 07:41:48 -06:00
gtsiam
c0bd3b362c
Custom classes for Process and Metrics (#13950)
* Subclass Process for audio_process

* Introduce custom mp.Process subclass

In preparation to switch the multiprocessing startup method away from
"fork", we cannot rely on os.fork cloning the log state at fork time.
Instead, we have to set up logging before we run the business logic of
each process.

* Make camera_metrics into a class

* Make ptz_metrics into a class

* Fixed PtzMotionEstimator.ptz_metrics type annotation

* Removed pointless variables

* Do not start audio processor when no audio cameras are configured
2024-09-27 07:53:23 -05:00
Josh Hawkins
ecbf0410eb
Regenerate genai tracked object descriptions (#13930)
* add genai to frigateconfig

* add regenerate button if genai is enabled

* add endpoint and new zmq pub/sub model

* move publisher to app

* dont override

* logging

* debug timeouts

* clean up

* clean up

* allow saving of empty description

* ensure descriptions can be empty

* update search detail when results change

* revalidate explore page on focus

* global mutate hook

* description websocket hook and dispatcher

* revalidation and mutation

* fix merge conflicts

* update tests

* fix merge conflicts

* fix response message

* fix response message

* fix fastapi

* fix test

* remove log

* json content

* fix content response

* more json content fixes

* another one
2024-09-24 08:14:51 -06:00
Rui Alves
cffc431bf0
Frigate HTTP API using FastAPI (#13871)
* POC: Added FastAPI with one endpoint (get /logs/service)

* POC: Revert error_log

* POC: Converted preview related endpoints to FastAPI

* POC: Converted two more endpoints to FastAPI

* POC: lint

* Convert all media endpoints to FastAPI. Added /media prefix (/media/camera && media/events && /media/preview)

* Convert all notifications API endpoints to FastAPI

* Convert first review API endpoints to FastAPI

* Convert remaining review API endpoints to FastAPI

* Convert export endpoints to FastAPI

* Fix path parameters

* Convert events endpoints to FastAPI

* Use body for multiple events endpoints

* Use body for multiple events endpoints (create and end event)

* Convert app endpoints to FastAPI

* Convert app endpoints to FastAPI

* Convert auth endpoints to FastAPI

* Removed flask app in favour of FastAPI app. Implemented FastAPI middleware to check CSRF, connect and disconnect from DB. Added middleware x-forwared-for headers

* Added starlette plugin to expose custom headers

* Use slowapi as the limiter

* Use query parameters for the frame latest endpoint

* Use query parameters for the media snapshot.jpg endpoint

* Use query parameters for the media MJPEG feed endpoint

* Revert initial nginx.conf change

* Added missing even_id for /events/search endpoint

* Removed left over comment

* Use FastAPI TestClient

* severity query parameter should be a string

* Use the same pattern for all tests

* Fix endpoint

* Revert media routers to old names. Order routes to make sure the dynamic ones from media.py are only used whenever there's no match on auth/etc

* Reverted paths for media on tsx files

* Deleted file

* Fix test_http to use TestClient

* Formatting

* Bind timeline to DB

* Fix http tests

* Replace filename with pathvalidate

* Fix latest.ext handling and disable uvicorn access logs

* Add cosntraints to api provided values

* Formatting

* Remove unused

* Remove unused

* Get rate limiter working

---------

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>
2024-09-24 07:05:30 -06:00
gtsiam
dc54981784
Move more things out of FrigateApp (#13897)
* Moved FrigateApp.init_config() into FrigateConfig.load()

* Move frigate config loading into main

* Store PlusApi in FrigateConfig

* Register SIGTERM handler in main

* Ensure logging is setup during config parsing

* Removed pointless try

* Moved config initialization out of FrigateApp

* Made FrigateApp.shm_frame_count into a function

* Removed log calls from signal handlers

python's logging calls are not re-entrant, which caused at least one of
these to deadlock randomly.

* Reopen stdout/err on process fork

This helps avoid deadlocks (https://github.com/python/cpython/issues/91776).

* Make mypy happy

* Whoops. I might have forgotten to save.

Truly an amateur mistake.

* Always call FrigateApp.stop()
2024-09-24 07:07:47 -05:00
gtsiam
e8763b3697
Removed usage of PyYAML for config parsing. (#13883)
* Ignore entire __pycache__ folder instead of individual *.pyc files

* Ignore .mypy_cache in git

* Rework config YAML parsing to use only ruamel.yaml

PyYAML silently overrides keys when encountering duplicates, but ruamel
raises and exception by default. Since we're already using it elsewhere,
dropping PyYAML is an easy choice to make.

* Added EnvString in config to slim down runtime_config()

* Added gitlens to devcontainer

* Automatically call FrigateConfig.runtime_config()

runtime_config needed to be called manually before. Now, it's been
removed, but the same code is run by a pydantic validator.

* Fix handling of missing -segment_time

* Removed type annotation on FrigateConfig's parse

I'd like to keep them, but then mypy complains about some fundamental
errors with how the pydantic model is structured. I'd like to fix it,
but I'd rather work towards moving some of this config to the database.
2024-09-22 10:56:57 -05:00
gtsiam
1c24f0054a
Make logging code self-contained (#13785)
* Make logging code self-contained.

Rewrite logging code to use python's builting QueueListener, effectively
moving the logging process into a thread of the Frigate app.

Also, wrap this behaviour in a easy-to-use context manager to encourage
some consistency.

* Fixed typing errors

* Remove todo note from log filter

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>

* Do not access log record's msg directly

* Clear all root handlers before starting app

---------

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>
2024-09-17 08:26:25 -05:00
Nicolas Mowen
5ff476c6f9
Configurable ffmpeg (#13722)
* Install multiple ffmpeg versions and add config to make it configurable

* Update docs

* Run ffprobe too

* Cleanup

* Apply config to go2rtc as well

* Fix ffmpeg bin

* Docs

* Restore path

* Cleanup env var

* Fix ffmpeg path for encoding

* Fix export

* Formatting
2024-09-13 15:14:51 -05:00
Nicolas Mowen
07d1692f2b
Make notifications toggleable via MQTT (#13657)
* Add ability to toggle mqtt state from MQTT / ws

* Listen to notification config updates

* Add docs for notifications
2024-09-10 11:24:44 -06:00
Nicolas Mowen
9afa1354da
Limit shm frame count (#12363)
* Limited shm frame count (#12346)

* Only keep 2x detect fps frames in SHM

* Don't delete previous shm frames in output

* Catch case where images do not exist

* Ensure files are closed

* Clear out all frames when shutting down

* Correct the number of frames saved

* Simplify empty shm error handling

* Improve frame safety

* Add handler logs when frame is None

* Don't fail on cleanup

* Cleanup logging

* Update docs

* Update calculation

* Restore condition

* Fix case where thumbnail is saved without frame

* Adjust debug logs

* Calculate best shm frame count

* Fix shm count calculation

* Catch missing frame

* Formatting

* Clarify docs

* Catch none frame in autotracking
2024-09-03 10:22:30 -06:00
Nicolas Mowen
3abf89596a Disable semantic search by default (#12568)
* Disable semantic search by default and don't start processes unless enabled

* Conditionally create embeddings

* Fix typing
2024-08-29 20:19:50 -06:00
Nicolas Mowen
690ee3dc15 Implement support for notifications (#12523)
* Setup basic notification page

* Add basic notification implementation

* Register for push notifications

* Implement dispatching

* Add fields

* Handle image and link

* Add notification config

* Add field for users notification tokens

* Implement saving of notification tokens

* Implement VAPID key generation

* Implement public key encoding

* Implement webpush from server

* Implement push notification handling

* Make notifications config only

* Add maskable icon

* Use zod form to control notification settings in the UI

* Use js

* Always open notification

* Support multiple endpoints

* Handle cleaning up expired notification registrations

* Correctly unsubscribe notifications

* Change ttl dynamically

* Add note about notification latency and features

* Cleanup docs

* Fix firefox pushes

* Add links to docs and improve formatting

* Improve wording

* Fix docstring

Co-authored-by: Blake Blackshear <blake@frigate.video>

* Handle case where native auth is not enabled

* Show errors in UI

---------

Co-authored-by: Blake Blackshear <blake@frigate.video>
2024-08-29 20:19:50 -06:00
Jason Hunter
9e825811f2 Semantic Search API (#12105)
* initial event search api implementation

* fix lint

* fix tests

* move chromadb imports and pysqlite hotswap to fix tests

* remove unused import

* switch default limit to 50

* fix events accidently pulling inside chroma results loop
2024-08-29 20:19:50 -06:00
Jason Hunter
36cbffcc5e Semantic Search for Detections (#11899)
* Initial re-implementation of semantic search

* put docker-compose back and make reindex match docs

* remove debug code and fix import

* fix docs

* manually build pysqlite3 as binaries are only available for x86-64

* update comment in build_pysqlite3.sh

* only embed objects

* better error handling when genai fails

* ask ollama to pull requested model at startup

* update ollama docs

* address some PR review comments

* fix lint

* use IPC to write description, update docs for reindex

* remove gemini-pro-vision from docs as it will be unavailable soon

* fix OpenAI doc available models

* fix api error in gemini and metadata for embeddings
2024-08-29 20:19:50 -06:00
Blake Blackshear
9ceffeb191
split out proxy from auth (#11963)
* split out proxy from auth

* update documentation

* fixup auth mode check
2024-06-14 18:02:13 -05:00
Blake Blackshear
30b86271ea
move clip.mp4 backend to clips folder (#11834)
* move clip.mp4 backend to clips folder

* improve caching

* fix check
2024-06-09 13:45:26 -05:00
Blake Blackshear
b4384a1be3
Shutdown hang (#11793)
* intentionally handle queues during shutdown and carefully manage shutdown order

* more carefully manage shutdown to avoid threadlocks

* use debug for signal logging

* ensure disabled cameras dont break shutdown

* typo
2024-06-06 18:54:38 -05:00
Blake Blackshear
1133202cbd
Auth! (#11347)
* reload the window on 401

* backend apis for auth

* add login page

* re-enable web linter

* fix login page routing

* bypass csrf for internal auth endpoint

* disable healthcheck in devcontainer target

* include login page in vite build

* redirect to login page on 401

* implement config for users and settings

* implement JWT actual secret

* add brute force protection on login

* add support for redirecting from auth failures on api calls

* return location for redirect

* default cookie name should pass regex test

* set hash iterations to current OWASP recommendation

* move users to database instead of config

* config option to reset admin password on startup

* user management UI

* check for deleted user on refresh

* validate username and fixes

* remove password constraint

* cleanup

* fix user check on refresh

* web fixes

* implement auth via new external port

* use x-forwarded-for to rate limit login attempts by ip

* implement logout and profile

* fixes

* lint fixes

* add support for user passthru from upstream proxies

* add support for specifying a logout url

* add documentation

* Update docs/docs/configuration/authentication.md

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>

* Update docs/docs/configuration/authentication.md

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>

---------

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>
2024-05-18 10:36:13 -06:00
Nicolas Mowen
4216d08099
Backend and webui fixes (#11309)
* Ensure that items without end times are set to not have a snapshot

* Save full frame if no frame is currently saved

* Webui fixes

* Cleanup
2024-05-09 08:20:33 -05:00
Josh Hawkins
2be15b6c01
Improve config validation error messages (#11292) 2024-05-08 08:46:31 -06:00
Nicolas Mowen
8c610bea49
Remove dev env var requirement and update docs for latest config (#10483)
* Update docs for alerts and event review

* Add docs for camera groups

* Update reference config with new config values

* Remove env variable requirement

* Add to sidebar

* Update snapshot docs

* add zones example to detection docs too

* Generalize the zone docs
2024-04-28 09:35:50 -05:00
Nicolas Mowen
baf363fcb0
Make a backup DB before doing migrations (#11048) 2024-04-20 08:55:51 -05:00
Nicolas Mowen
fe4fb645d3
Save exports to database (#11040)
* Save review thumbs in dedicated folder

* Create exports table

* Save exports to DB and save thumbnail for export

* Save full frame always

* Fix rounded corners

* Save exports that are in progress

* No need to remove spaces

* Reorganize apis to use IDs

* Use new apis for frontend

* Get video playback working

* Fix deleting and renaming

* Import existing exports to DB

* Implement downloading

* Formatting
2024-04-19 17:11:41 -05:00
Nicolas Mowen
3788df5bc6
Implement config migration and restructure config for new review format (#10961)
* Update reference config to reflect new config

* Migrate 0.13 config to match 0.14 config style

* Overwrite existing config

* Adjust config schema to remove events required zones and include reviews

* Update object config to check correct required zones config

* Refactor reviews to remove motion and only create review segments in expected circumstances

* Cleanup

* Formatting

* Fix update ordering

* Update pydantic

* Remove rtmp references as part of migration

* Catch file not found for alert frame
2024-04-13 06:08:20 -06:00
Nicolas Mowen
049f27d710
Ongoing review segments (#10924)
* Update review maintainer to save events when ongoing

* Handle previews for in progress review items

* Reset DB items in app

* Handle in progress review items

* Scroll back down to selected event item

* Handle undefined end time

* Formatting

* remove unused

* Make export handles have full resolution

* reduce preview thumbnail props

* fix missing return

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>

---------

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2024-04-11 07:42:16 -05:00
Nicolas Mowen
8163c036ef
Use zmq for event end queue and update python deps (#10886)
* Use zmq for events ended

* Cleanup

* Update deps

* formatting
2024-04-08 18:19:45 -05:00
Nicolas Mowen
07ee39b9b8
Write default config if no config is saved (#10847) 2024-04-05 08:39:43 -05:00
Nicolas Mowen
fb7cfe5471
Implement camera stats graphs (#10831)
* Implement camera graphs

* Cleanup naming

* Cleanup rendering

* Cleanup spacing

* Fix audio name

* theme updates to match design corretly

* Mobile color fixes

* Mobile color fixes
2024-04-04 15:55:04 -05:00
Nicolas Mowen
559e6910c4
Improve restart timing (#10709) 2024-03-27 10:03:13 -05:00
Nicolas Mowen
76a114a3cd
Rewrite events communication to use zmq instead of mp.Queue (#10627)
* Move to using zmq for events updating

* Use event updater in manual events handler

* Formatting
2024-03-23 11:11:32 -05:00
Nicolas Mowen
3c4b1fb6f2
Update flask and restructure into api folder with apis put into separate folders (#10193)
* Update flask

* Update flask and break apart different sections into different files

* formatting

* Fix test and add safety check
2024-03-02 22:10:37 +00:00
Nicolas Mowen
33c77d03c7
Reorganize stats (#9960)
* Reorganize stats

* Fix tests
2024-02-21 14:10:28 -06:00
Nicolas Mowen
940be5dc6f
Create ReviewSegment table in DB for organizing detections to be reviewed (#9918)
* Add review to database

* Create main manager for review segments

* Upsert and maintain review segments

* Update logic for adding new segments

* Add api

* Support deleting review segments on recording cleanup

* Add field for alert labels

* Formatting

* Logic fixes

* Save 16:9 thumbnail for review segment

* Ensure that crop is 16:9

* Fix non detected objects being added

* Only include true positives

* Add sub labels to data
2024-02-20 16:26:09 -07:00
Nicolas Mowen
dba21b606d
Convert config updating and video/audio queues to use zmq (#9893)
* Add config pub / sub pattern

* remove recording from feature metrics

* remove audio and feature metrics

* Check for updates from all cameras

* remove birdseye from camera metrics

* remove motion and detection camera metrics

* Ensure that all processes are stopped

* Stop communicators

* Detections

* Cleanup video output queue

* Use select for time sensitive polls

* Use ipc instead of tcp
2024-02-19 07:26:59 -06:00
Nicolas Mowen
dd3dc7949a
Use zmq for inter process communication (#9309)
* Use zmq for inter process communication

* Use localhost for reply and request

* Use pyobj instead of json and Need to use separate requestors for each audio listener

* Cleanup port defining
2024-02-14 18:24:36 -06:00
Josh Hawkins
764736b223
update dev builds message (#9853) 2024-02-14 18:12:33 -06:00
Nicolas Mowen
64988c9be0
Streamline live view (#9772)
* Break out live page

* Improving layouts and add chip component

* Improve default camera player sizing

* Improve live updating

* Cleanup and fit figma

* Use fixed height

* Masonry layout

* Fix stuff

* Don't force heights

* Adjust scaling

* Cleanup

* remove sidebar (#9731)

* remove sidebar

* keep sidebar on mobile for now and add icons

* Fix revalidation

* Cleanup

* Cleanup width

* Add chips for activity on cameras

* Remove dashboard from header

* Use Inter font (#9735)

* Show still image when no activity is occurring

* remove unused search params

* add playing check for webrtc

* Don't use grid at all for single column

* Fix height on mobile

* a few style updates to better match figma (#9745)

* Remove active objects when they become stationary

* Move to sidebar only and make settings separate component

* Fix layout

* Animate visibility of chips

* Sidebar is full screen

* Fix tall aspect ratio cameras

* Fix complicated aspect logic

* remove

* Adjust thumbnail aspect and add text

* margin on single column layout

* Smaller event thumb text

* Simplify basic image view

* Only show the red dot when camera is recording

* Improve typing for camera toggles

* animate chips with react-transition-group (#9763)

* don't flash when going to still image

* revalidate

* tooltips and active tracking outline (#9766)

* tooltips

* fix tooltip provider and add active tracking outline

* remove unused icon

* remove figma comment

* Get live mode working for jsmpeg

* add small gradient below timeago on event thumbnails (#9767)

* Create live mode hook and make sure jsmpeg can be used

* Enforce env var

* Use print

* Remove unstable

* Add tooltips to thumbnails

* Put back vite

* Format

* Update web/src/components/player/JSMpegPlayer.tsx

---------

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
Co-authored-by: Blake Blackshear <blake@frigate.video>
2024-02-10 05:30:53 -07:00