forked from Github/frigate
Compare commits
155 Commits
model-fixe
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c71bb53e8b | ||
|
|
717493e668 | ||
|
|
d49f958d4d | ||
|
|
33ee32865f | ||
|
|
17f8939f97 | ||
|
|
1b7fe9523d | ||
|
|
0763f56047 | ||
|
|
1ea282fba8 | ||
|
|
869fa2631e | ||
|
|
f336a91fee | ||
|
|
d302b6e198 | ||
|
|
ed2e1f3f72 | ||
|
|
b4d82084a9 | ||
|
|
53b96dfb89 | ||
|
|
0e3fb6cbdd | ||
|
|
6b12a45a95 | ||
|
|
0b9c4c18dd | ||
|
|
d0cc8cb64b | ||
|
|
bb86e71e65 | ||
|
|
8aa6297308 | ||
|
|
d3b631a952 | ||
|
|
47d495fc01 | ||
|
|
32322b23b2 | ||
|
|
c0ba98e26f | ||
|
|
a5a7cd3107 | ||
|
|
a729408599 | ||
|
|
4dddc53735 | ||
|
|
5f42caad03 | ||
|
|
5475672a9d | ||
|
|
833cdcb6d2 | ||
|
|
c95bc9fe44 | ||
|
|
a1fa9decad | ||
|
|
4a5fe4138e | ||
|
|
002fdeae67 | ||
|
|
5802a66469 | ||
|
|
71e8f75a01 | ||
|
|
ee816b2251 | ||
|
|
f094c59cd0 | ||
|
|
d25ffdb292 | ||
|
|
2207a91f7b | ||
|
|
33957e5360 | ||
|
|
ff92b13f35 | ||
|
|
e76f4e9bd9 | ||
|
|
0df091f387 | ||
|
|
66277fbb6c | ||
|
|
a67ff3843a | ||
|
|
9ae839ad72 | ||
|
|
66f71aecf7 | ||
|
|
0b203a3673 | ||
|
|
26c3f9f914 | ||
|
|
474c248c9d | ||
|
|
5b1b6b5be0 | ||
|
|
45e9030358 | ||
|
|
f9c1600f0d | ||
|
|
ad85f8882b | ||
|
|
206ed06905 | ||
|
|
e407ba47c2 | ||
|
|
7fdf42a56f | ||
|
|
4eea541352 | ||
|
|
ed9c67804a | ||
|
|
9c20cd5f7b | ||
|
|
6c86827d3a | ||
|
|
d2b2f3d54d | ||
|
|
64b3397f8e | ||
|
|
0829517b72 | ||
|
|
c1bfc1df67 | ||
|
|
96c0c43dc8 | ||
|
|
a68c7f4ef8 | ||
|
|
7c474e6827 | ||
|
|
143bab87f1 | ||
|
|
580f35112e | ||
|
|
3249ffb273 | ||
|
|
7bae9463b2 | ||
|
|
ae30ac6e3c | ||
|
|
46ed520886 | ||
|
|
ace02a6dfa | ||
|
|
0d59754be2 | ||
|
|
15bd26c9b1 | ||
|
|
bc371acb3e | ||
|
|
2eb5fbf112 | ||
|
|
fc0fb158d5 | ||
|
|
404807c697 | ||
|
|
29ea7c53f2 | ||
|
|
1fc4af9c86 | ||
|
|
ac762762c3 | ||
|
|
553676aade | ||
|
|
a13b9815f6 | ||
|
|
156e7cc628 | ||
|
|
959ca0f412 | ||
|
|
9755fa0537 | ||
|
|
77ec86d31a | ||
|
|
189d4b459f | ||
|
|
44f40966e7 | ||
|
|
7d3313e732 | ||
|
|
591b50dfa7 | ||
|
|
27ef661fec | ||
|
|
d7935abc14 | ||
|
|
11068aa9d0 | ||
|
|
1234003527 | ||
|
|
e5ebf938f6 | ||
|
|
8c2c07fd18 | ||
|
|
9e1a50c3be | ||
|
|
ac8ddada0b | ||
|
|
885485da70 | ||
|
|
bb4e863e87 | ||
|
|
c7a4220d65 | ||
|
|
03dd9b2d42 | ||
|
|
89ca085b94 | ||
|
|
fffd9defea | ||
|
|
d10fea6012 | ||
|
|
ab26aee8b2 | ||
|
|
bb80a7b2ee | ||
|
|
e4a6b29279 | ||
|
|
d12c7809dd | ||
|
|
357ce0382e | ||
|
|
73da3d9b20 | ||
|
|
e67b7a6d5e | ||
|
|
4e25bebdd0 | ||
|
|
abd22d2566 | ||
|
|
8aeb597780 | ||
|
|
33825f6d96 | ||
|
|
eca504cb07 | ||
|
|
4c75440af4 | ||
|
|
94f7528885 | ||
|
|
4dadf6d353 | ||
|
|
2d27e72ed9 | ||
|
|
4ff0c8a8d1 | ||
|
|
f9fba94863 | ||
|
|
f9b246dbd0 | ||
|
|
8fefded8dc | ||
|
|
18824830fd | ||
|
|
fa81d87dc0 | ||
|
|
8bc145472a | ||
|
|
7afc1e9762 | ||
|
|
fc59c83e16 | ||
|
|
e4048be088 | ||
|
|
d715a8c290 | ||
|
|
ad308252a1 | ||
|
|
c7d9f83638 | ||
|
|
828fdbfd2d | ||
|
|
40c6fda19d | ||
|
|
b69816c2f9 | ||
|
|
46f5234bd9 | ||
|
|
81b8d7a66b | ||
|
|
b1285a16c1 | ||
|
|
90140e7710 | ||
|
|
8364e68667 | ||
|
|
4bb420d049 | ||
|
|
560dc68120 | ||
|
|
8fcb8e54f7 | ||
|
|
af844ea9d5 | ||
|
|
51509760e3 | ||
|
|
f86957e5e1 | ||
|
|
2a15b95f18 | ||
|
|
039ab1ccd7 |
@@ -12,6 +12,7 @@ argmax
|
||||
argmin
|
||||
argpartition
|
||||
ascontiguousarray
|
||||
astype
|
||||
authelia
|
||||
authentik
|
||||
autodetected
|
||||
@@ -42,6 +43,7 @@ codeproject
|
||||
colormap
|
||||
colorspace
|
||||
comms
|
||||
coro
|
||||
ctypeslib
|
||||
CUDA
|
||||
Cuvid
|
||||
@@ -59,6 +61,7 @@ dsize
|
||||
dtype
|
||||
ECONNRESET
|
||||
edgetpu
|
||||
fastapi
|
||||
faststart
|
||||
fflags
|
||||
ffprobe
|
||||
@@ -193,6 +196,7 @@ poweroff
|
||||
preexec
|
||||
probesize
|
||||
protobuf
|
||||
pstate
|
||||
psutil
|
||||
pubkey
|
||||
putenv
|
||||
@@ -237,6 +241,7 @@ sleeptime
|
||||
SNDMORE
|
||||
socs
|
||||
sqliteq
|
||||
sqlitevecq
|
||||
ssdlite
|
||||
statm
|
||||
stimeout
|
||||
@@ -271,9 +276,11 @@ unraid
|
||||
unreviewed
|
||||
userdata
|
||||
usermod
|
||||
uvicorn
|
||||
vaapi
|
||||
vainfo
|
||||
variations
|
||||
vbios
|
||||
vconcat
|
||||
vitb
|
||||
vstream
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
set -euxo pipefail
|
||||
|
||||
# Cleanup the old github host key
|
||||
sed -i -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d' ~/.ssh/known_hosts
|
||||
# Add new github host key
|
||||
curl -L https://api.github.com/meta | jq -r '.ssh_keys | .[]' | \
|
||||
sed -e 's/^/github.com /' >> ~/.ssh/known_hosts
|
||||
if [[ -f ~/.ssh/known_hosts ]]; then
|
||||
# Add new github host key
|
||||
sed -i -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31\/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi\/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==/d' ~/.ssh/known_hosts
|
||||
curl -L https://api.github.com/meta | jq -r '.ssh_keys | .[]' | \
|
||||
sed -e 's/^/github.com /' >> ~/.ssh/known_hosts
|
||||
fi
|
||||
|
||||
# Frigate normal container runs as root, so it have permission to create
|
||||
# the folders. But the devcontainer runs as the host user, so we need to
|
||||
|
||||
1
.github/pull_request_template.md
vendored
1
.github/pull_request_template.md
vendored
@@ -13,6 +13,7 @@
|
||||
- [ ] New feature
|
||||
- [ ] Breaking change (fix/feature causing existing functionality to break)
|
||||
- [ ] Code quality improvements to existing code
|
||||
- [ ] Documentation Update
|
||||
|
||||
## Additional information
|
||||
|
||||
|
||||
16
.github/workflows/ci.yml
vendored
16
.github/workflows/ci.yml
vendored
@@ -6,6 +6,8 @@ on:
|
||||
branches:
|
||||
- dev
|
||||
- master
|
||||
paths-ignore:
|
||||
- "docs/**"
|
||||
|
||||
# only run the latest commit to avoid cache overwrites
|
||||
concurrency:
|
||||
@@ -22,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
|
||||
@@ -43,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
|
||||
@@ -84,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
|
||||
@@ -110,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
|
||||
@@ -138,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
|
||||
@@ -163,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
|
||||
@@ -186,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
|
||||
|
||||
24
.github/workflows/dependabot-auto-merge.yaml
vendored
24
.github/workflows/dependabot-auto-merge.yaml
vendored
@@ -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 }}
|
||||
15
.github/workflows/pull_request.yml
vendored
15
.github/workflows/pull_request.yml
vendored
@@ -1,6 +1,9 @@
|
||||
name: On pull request
|
||||
|
||||
on: pull_request
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- "docs/**"
|
||||
|
||||
env:
|
||||
DEFAULT_PYTHON: 3.9
|
||||
@@ -16,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
|
||||
@@ -35,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
|
||||
@@ -49,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
|
||||
@@ -64,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:
|
||||
@@ -85,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
|
||||
|
||||
13
.github/workflows/release.yml
vendored
13
.github/workflows/release.yml
vendored
@@ -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
|
||||
@@ -34,14 +39,14 @@ jobs:
|
||||
STABLE_TAG=${BASE}:stable
|
||||
PULL_TAG=${BASE}:${BUILD_TAG}
|
||||
docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG} docker://${VERSION_TAG}
|
||||
for variant in standard-arm64 tensorrt tensorrt-jp4 tensorrt-jp5 rk; do
|
||||
for variant in standard-arm64 tensorrt tensorrt-jp4 tensorrt-jp5 rk h8l rocm; do
|
||||
docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG}-${variant} docker://${VERSION_TAG}-${variant}
|
||||
done
|
||||
|
||||
# stable tag
|
||||
if [[ "${BUILD_TYPE}" == "stable" ]]; then
|
||||
docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG} docker://${STABLE_TAG}
|
||||
for variant in standard-arm64 tensorrt tensorrt-jp4 tensorrt-jp5 rk; do
|
||||
for variant in standard-arm64 tensorrt tensorrt-jp4 tensorrt-jp5 rk h8l rocm; do
|
||||
docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG}-${variant} docker://${STABLE_TAG}-${variant}
|
||||
done
|
||||
fi
|
||||
|
||||
5
.github/workflows/stale.yml
vendored
5
.github/workflows/stale.yml
vendored
@@ -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
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ services:
|
||||
# count: 1
|
||||
# capabilities: [gpu]
|
||||
environment:
|
||||
YOLO_MODELS: yolov7-320
|
||||
YOLO_MODELS: ""
|
||||
devices:
|
||||
- /dev/bus/usb:/dev/bus/usb
|
||||
# - /dev/dri:/dev/dri # for intel hwaccel, needs to be updated for your hardware
|
||||
|
||||
@@ -16,89 +16,25 @@ RUN mkdir /h8l-wheels
|
||||
# Build the wheels
|
||||
RUN pip3 wheel --wheel-dir=/h8l-wheels -c /requirements-wheels.txt -r /requirements-wheels-h8l.txt
|
||||
|
||||
# Build HailoRT and create wheel
|
||||
FROM wheels AS build-hailort
|
||||
FROM wget AS hailort
|
||||
ARG TARGETARCH
|
||||
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
|
||||
# Install necessary APT packages
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install -y \
|
||||
apt-transport-https \
|
||||
gnupg \
|
||||
wget \
|
||||
# the key fingerprint can be obtained from https://ftp-master.debian.org/keys.html
|
||||
&& wget -qO- "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xA4285295FC7B1A81600062A9605C66F00D6C9793" | \
|
||||
gpg --dearmor > /usr/share/keyrings/debian-archive-bullseye-stable.gpg \
|
||||
&& echo "deb [signed-by=/usr/share/keyrings/debian-archive-bullseye-stable.gpg] http://deb.debian.org/debian bullseye main contrib non-free" | \
|
||||
tee /etc/apt/sources.list.d/debian-bullseye-nonfree.list \
|
||||
&& apt-get -qq update \
|
||||
&& apt-get -qq install -y \
|
||||
python3.9 \
|
||||
python3.9-dev \
|
||||
build-essential cmake git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Extract Python version and set environment variables
|
||||
RUN PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}' | cut -d. -f1,2) && \
|
||||
PYTHON_VERSION_NO_DOT=$(echo $PYTHON_VERSION | sed 's/\.//') && \
|
||||
echo "PYTHON_VERSION=$PYTHON_VERSION" > /etc/environment && \
|
||||
echo "PYTHON_VERSION_NO_DOT=$PYTHON_VERSION_NO_DOT" >> /etc/environment
|
||||
|
||||
# Clone and build HailoRT
|
||||
RUN . /etc/environment && \
|
||||
git clone https://github.com/hailo-ai/hailort.git /opt/hailort && \
|
||||
cd /opt/hailort && \
|
||||
git checkout v4.18.0 && \
|
||||
cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Release -DHAILO_BUILD_PYBIND=1 -DPYBIND11_PYTHON_VERSION=${PYTHON_VERSION} && \
|
||||
cmake --build build --config release --target libhailort && \
|
||||
cmake --build build --config release --target _pyhailort && \
|
||||
cp build/hailort/libhailort/bindings/python/src/_pyhailort.cpython-${PYTHON_VERSION_NO_DOT}-$(if [ $TARGETARCH == "amd64" ]; then echo 'x86_64'; else echo 'aarch64'; fi )-linux-gnu.so hailort/libhailort/bindings/python/platform/hailo_platform/pyhailort/ && \
|
||||
cp build/hailort/libhailort/src/libhailort.so hailort/libhailort/bindings/python/platform/hailo_platform/pyhailort/
|
||||
|
||||
RUN ls -ahl /opt/hailort/build/hailort/libhailort/src/
|
||||
RUN ls -ahl /opt/hailort/hailort/libhailort/bindings/python/platform/hailo_platform/pyhailort/
|
||||
|
||||
# Remove the existing setup.py if it exists in the target directory
|
||||
RUN rm -f /opt/hailort/hailort/libhailort/bindings/python/platform/setup.py
|
||||
|
||||
# Copy generate_wheel_conf.py and setup.py
|
||||
COPY docker/hailo8l/pyhailort_build_scripts/generate_wheel_conf.py /opt/hailort/hailort/libhailort/bindings/python/platform/generate_wheel_conf.py
|
||||
COPY docker/hailo8l/pyhailort_build_scripts/setup.py /opt/hailort/hailort/libhailort/bindings/python/platform/setup.py
|
||||
|
||||
# Run the generate_wheel_conf.py script
|
||||
RUN python3 /opt/hailort/hailort/libhailort/bindings/python/platform/generate_wheel_conf.py
|
||||
|
||||
# Create a wheel file using pip3 wheel
|
||||
RUN cd /opt/hailort/hailort/libhailort/bindings/python/platform && \
|
||||
python3 setup.py bdist_wheel --dist-dir /hailo-wheels
|
||||
RUN --mount=type=bind,source=docker/hailo8l/install_hailort.sh,target=/deps/install_hailort.sh \
|
||||
/deps/install_hailort.sh
|
||||
|
||||
# Use deps as the base image
|
||||
FROM deps AS h8l-frigate
|
||||
|
||||
# Copy the wheels from the wheels stage
|
||||
COPY --from=h8l-wheels /h8l-wheels /deps/h8l-wheels
|
||||
COPY --from=build-hailort /hailo-wheels /deps/hailo-wheels
|
||||
COPY --from=build-hailort /etc/environment /etc/environment
|
||||
RUN CC=$(python3 -c "import sysconfig; import shlex; cc = sysconfig.get_config_var('CC'); cc_cmd = shlex.split(cc)[0]; print(cc_cmd[:-4] if cc_cmd.endswith('-gcc') else cc_cmd)") && \
|
||||
echo "CC=$CC" >> /etc/environment
|
||||
COPY --from=hailort /hailo-wheels /deps/hailo-wheels
|
||||
COPY --from=hailort /rootfs/ /
|
||||
|
||||
# Install the wheels
|
||||
RUN pip3 install -U /deps/h8l-wheels/*.whl
|
||||
RUN pip3 install -U /deps/hailo-wheels/*.whl
|
||||
|
||||
RUN . /etc/environment && \
|
||||
mv /usr/local/lib/python${PYTHON_VERSION}/dist-packages/hailo_platform/pyhailort/libhailort.so /usr/lib/${CC} && \
|
||||
cd /usr/lib/${CC}/ && \
|
||||
ln -s libhailort.so libhailort.so.4.18.0
|
||||
|
||||
# Copy base files from the rootfs stage
|
||||
COPY --from=rootfs / /
|
||||
|
||||
# Set environment variables for Hailo SDK
|
||||
ENV PATH="/opt/hailort/bin:${PATH}"
|
||||
ENV LD_LIBRARY_PATH="/usr/lib/$(if [ $TARGETARCH == "amd64" ]; then echo 'x86_64'; else echo 'aarch64'; fi )-linux-gnu:${LD_LIBRARY_PATH}"
|
||||
|
||||
# Set workdir
|
||||
WORKDIR /opt/frigate/
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
target wget {
|
||||
dockerfile = "docker/main/Dockerfile"
|
||||
platforms = ["linux/arm64","linux/amd64"]
|
||||
target = "wget"
|
||||
}
|
||||
|
||||
target wheels {
|
||||
dockerfile = "docker/main/Dockerfile"
|
||||
platforms = ["linux/arm64","linux/amd64"]
|
||||
@@ -19,6 +25,7 @@ target rootfs {
|
||||
target h8l {
|
||||
dockerfile = "docker/hailo8l/Dockerfile"
|
||||
contexts = {
|
||||
wget = "target:wget"
|
||||
wheels = "target:wheels"
|
||||
deps = "target:deps"
|
||||
rootfs = "target:rootfs"
|
||||
|
||||
19
docker/hailo8l/install_hailort.sh
Executable file
19
docker/hailo8l/install_hailort.sh
Executable file
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
hailo_version="4.19.0"
|
||||
|
||||
if [[ "${TARGETARCH}" == "amd64" ]]; then
|
||||
arch="x86_64"
|
||||
elif [[ "${TARGETARCH}" == "arm64" ]]; then
|
||||
arch="aarch64"
|
||||
fi
|
||||
|
||||
wget -qO- "https://github.com/frigate-nvr/hailort/releases/download/v${hailo_version}/hailort-${TARGETARCH}.tar.gz" |
|
||||
tar -C / -xzf -
|
||||
|
||||
mkdir -p /hailo-wheels
|
||||
|
||||
wget -P /hailo-wheels/ "https://github.com/frigate-nvr/hailort/releases/download/v${hailo_version}/hailort-${hailo_version}-cp39-cp39-linux_${arch}.whl"
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import sysconfig
|
||||
|
||||
|
||||
def extract_toolchain_info(compiler):
|
||||
# Remove the "-gcc" or "-g++" suffix if present
|
||||
if compiler.endswith("-gcc") or compiler.endswith("-g++"):
|
||||
compiler = compiler.rsplit("-", 1)[0]
|
||||
|
||||
# Extract the toolchain and ABI part (e.g., "gnu")
|
||||
toolchain_parts = compiler.split("-")
|
||||
abi_conventions = next(
|
||||
(part for part in toolchain_parts if part in ["gnu", "musl", "eabi", "uclibc"]),
|
||||
"",
|
||||
)
|
||||
|
||||
return abi_conventions
|
||||
|
||||
|
||||
def generate_wheel_conf():
|
||||
conf_file_path = os.path.join(
|
||||
os.path.abspath(os.path.dirname(__file__)), "wheel_conf.json"
|
||||
)
|
||||
|
||||
# Extract current system and Python version information
|
||||
py_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
|
||||
arch = platform.machine()
|
||||
system = platform.system().lower()
|
||||
libc_version = platform.libc_ver()[1]
|
||||
|
||||
# Get the compiler information
|
||||
compiler = sysconfig.get_config_var("CC")
|
||||
abi_conventions = extract_toolchain_info(compiler)
|
||||
|
||||
# Create the new configuration data
|
||||
new_conf_data = {
|
||||
"py_version": py_version,
|
||||
"arch": arch,
|
||||
"system": system,
|
||||
"libc_version": libc_version,
|
||||
"abi": abi_conventions,
|
||||
"extension": {
|
||||
"posix": "so",
|
||||
"nt": "pyd", # Windows
|
||||
}[os.name],
|
||||
}
|
||||
|
||||
# If the file exists, load the existing data
|
||||
if os.path.isfile(conf_file_path):
|
||||
with open(conf_file_path, "r") as conf_file:
|
||||
conf_data = json.load(conf_file)
|
||||
# Update the existing data with the new data
|
||||
conf_data.update(new_conf_data)
|
||||
else:
|
||||
# If the file does not exist, use the new data
|
||||
conf_data = new_conf_data
|
||||
|
||||
# Write the updated data to the file
|
||||
with open(conf_file_path, "w") as conf_file:
|
||||
json.dump(conf_data, conf_file, indent=4)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_wheel_conf()
|
||||
@@ -1,111 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from setuptools import find_packages, setup
|
||||
from wheel.bdist_wheel import bdist_wheel as orig_bdist_wheel
|
||||
|
||||
|
||||
class NonPurePythonBDistWheel(orig_bdist_wheel):
|
||||
"""Makes the wheel platform-dependent so it can be based on the _pyhailort architecture"""
|
||||
|
||||
def finalize_options(self):
|
||||
orig_bdist_wheel.finalize_options(self)
|
||||
self.root_is_pure = False
|
||||
|
||||
|
||||
def _get_hailort_lib_path():
|
||||
lib_filename = "libhailort.so"
|
||||
lib_path = os.path.join(
|
||||
os.path.abspath(os.path.dirname(__file__)),
|
||||
f"hailo_platform/pyhailort/{lib_filename}",
|
||||
)
|
||||
if os.path.exists(lib_path):
|
||||
print(f"Found libhailort shared library at: {lib_path}")
|
||||
else:
|
||||
print(f"Error: libhailort shared library not found at: {lib_path}")
|
||||
raise FileNotFoundError(f"libhailort shared library not found at: {lib_path}")
|
||||
return lib_path
|
||||
|
||||
|
||||
def _get_pyhailort_lib_path():
|
||||
conf_file_path = os.path.join(
|
||||
os.path.abspath(os.path.dirname(__file__)), "wheel_conf.json"
|
||||
)
|
||||
if not os.path.isfile(conf_file_path):
|
||||
raise FileNotFoundError(f"Configuration file not found: {conf_file_path}")
|
||||
|
||||
with open(conf_file_path, "r") as conf_file:
|
||||
content = json.load(conf_file)
|
||||
py_version = content["py_version"]
|
||||
arch = content["arch"]
|
||||
system = content["system"]
|
||||
extension = content["extension"]
|
||||
abi = content["abi"]
|
||||
|
||||
# Construct the filename directly
|
||||
lib_filename = f"_pyhailort.cpython-{py_version.split('cp')[1]}-{arch}-{system}-{abi}.{extension}"
|
||||
lib_path = os.path.join(
|
||||
os.path.abspath(os.path.dirname(__file__)),
|
||||
f"hailo_platform/pyhailort/{lib_filename}",
|
||||
)
|
||||
|
||||
if os.path.exists(lib_path):
|
||||
print(f"Found _pyhailort shared library at: {lib_path}")
|
||||
else:
|
||||
print(f"Error: _pyhailort shared library not found at: {lib_path}")
|
||||
raise FileNotFoundError(
|
||||
f"_pyhailort shared library not found at: {lib_path}"
|
||||
)
|
||||
|
||||
return lib_path
|
||||
|
||||
|
||||
def _get_package_paths():
|
||||
packages = []
|
||||
pyhailort_lib = _get_pyhailort_lib_path()
|
||||
hailort_lib = _get_hailort_lib_path()
|
||||
if pyhailort_lib:
|
||||
packages.append(pyhailort_lib)
|
||||
if hailort_lib:
|
||||
packages.append(hailort_lib)
|
||||
packages.append(os.path.abspath("hailo_tutorials/notebooks/*"))
|
||||
packages.append(os.path.abspath("hailo_tutorials/hefs/*"))
|
||||
return packages
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
setup(
|
||||
author="Hailo team",
|
||||
author_email="contact@hailo.ai",
|
||||
cmdclass={
|
||||
"bdist_wheel": NonPurePythonBDistWheel,
|
||||
},
|
||||
description="HailoRT",
|
||||
entry_points={
|
||||
"console_scripts": [
|
||||
"hailo=hailo_platform.tools.hailocli.main:main",
|
||||
]
|
||||
},
|
||||
install_requires=[
|
||||
"argcomplete",
|
||||
"contextlib2",
|
||||
"future",
|
||||
"netaddr",
|
||||
"netifaces",
|
||||
"verboselogs",
|
||||
"numpy==1.23.3",
|
||||
],
|
||||
name="hailort",
|
||||
package_data={
|
||||
"hailo_platform": _get_package_paths(),
|
||||
},
|
||||
packages=find_packages(),
|
||||
platforms=[
|
||||
"linux_x86_64",
|
||||
"linux_aarch64",
|
||||
"win_amd64",
|
||||
],
|
||||
url="https://hailo.ai/",
|
||||
version="4.17.0",
|
||||
zip_safe=False,
|
||||
)
|
||||
@@ -13,7 +13,7 @@ else
|
||||
fi
|
||||
|
||||
# Clone the HailoRT driver repository
|
||||
git clone --depth 1 --branch v4.18.0 https://github.com/hailo-ai/hailort-drivers.git
|
||||
git clone --depth 1 --branch v4.19.0 https://github.com/hailo-ai/hailort-drivers.git
|
||||
|
||||
# Build and install the HailoRT driver
|
||||
cd hailort-drivers/linux/pcie
|
||||
@@ -38,7 +38,7 @@ cd ../../
|
||||
if [ ! -d /lib/firmware/hailo ]; then
|
||||
sudo mkdir /lib/firmware/hailo
|
||||
fi
|
||||
sudo mv hailo8_fw.4.17.0.bin /lib/firmware/hailo/hailo8_fw.bin
|
||||
sudo mv hailo8_fw.*.bin /lib/firmware/hailo/hailo8_fw.bin
|
||||
|
||||
# Install udev rules
|
||||
sudo cp ./linux/pcie/51-hailo-udev.rules /etc/udev/rules.d/
|
||||
|
||||
@@ -211,6 +211,9 @@ ENV TOKENIZERS_PARALLELISM=true
|
||||
# https://github.com/huggingface/transformers/issues/27214
|
||||
ENV TRANSFORMERS_NO_ADVISORY_WARNINGS=1
|
||||
|
||||
# Set OpenCV ffmpeg loglevel to fatal: https://ffmpeg.org/doxygen/trunk/log_8h.html
|
||||
ENV OPENCV_FFMPEG_LOGLEVEL=8
|
||||
|
||||
ENV PATH="/usr/local/go2rtc/bin:/usr/local/tempio/bin:/usr/local/nginx/sbin:${PATH}"
|
||||
ENV LIBAVFORMAT_VERSION_MAJOR=60
|
||||
|
||||
|
||||
@@ -87,8 +87,8 @@ if [[ "${TARGETARCH}" == "amd64" ]]; then
|
||||
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/intel-graphics.gpg] https://repositories.intel.com/gpu/ubuntu jammy client" | tee /etc/apt/sources.list.d/intel-gpu-jammy.list
|
||||
apt-get -qq update
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
intel-opencl-icd intel-level-zero-gpu intel-media-va-driver-non-free \
|
||||
libmfx1 libmfxgen1 libvpl2
|
||||
intel-opencl-icd=24.35.30872.31-996~22.04 intel-level-zero-gpu=1.3.29735.27-914~22.04 intel-media-va-driver-non-free=24.3.3-996~22.04 \
|
||||
libmfx1=23.2.2-880~22.04 libmfxgen1=24.2.4-914~22.04 libvpl2=1:2.13.0.0-996~22.04
|
||||
|
||||
rm -f /usr/share/keyrings/intel-graphics.gpg
|
||||
rm -f /etc/apt/sources.list.d/intel-gpu-jammy.list
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
click == 8.1.*
|
||||
# FastAPI
|
||||
aiohttp == 3.11.2
|
||||
starlette == 0.41.2
|
||||
starlette-context == 0.3.6
|
||||
fastapi == 0.115.0
|
||||
uvicorn == 0.30.*
|
||||
slowapi == 0.1.9
|
||||
fastapi == 0.115.*
|
||||
uvicorn == 0.34.*
|
||||
slowapi == 0.1.*
|
||||
imutils == 0.5.*
|
||||
joserfc == 1.0.*
|
||||
pathvalidate == 3.2.*
|
||||
@@ -16,10 +18,10 @@ paho-mqtt == 2.1.*
|
||||
pandas == 2.2.*
|
||||
peewee == 3.17.*
|
||||
peewee_migrate == 1.13.*
|
||||
psutil == 5.9.*
|
||||
psutil == 6.1.*
|
||||
pydantic == 2.8.*
|
||||
git+https://github.com/fbcotter/py3nvml#egg=py3nvml
|
||||
pytz == 2024.1
|
||||
pytz == 2024.*
|
||||
pyzmq == 26.2.*
|
||||
ruamel.yaml == 0.18.*
|
||||
tzlocal == 5.2
|
||||
|
||||
@@ -165,7 +165,7 @@ if config.get("birdseye", {}).get("restream", False):
|
||||
birdseye: dict[str, any] = config.get("birdseye")
|
||||
|
||||
input = f"-f rawvideo -pix_fmt yuv420p -video_size {birdseye.get('width', 1280)}x{birdseye.get('height', 720)} -r 10 -i {BIRDSEYE_PIPE}"
|
||||
ffmpeg_cmd = f"exec:{parse_preset_hardware_acceleration_encode(ffmpeg_path, config.get('ffmpeg', {}).get('hwaccel_args'), input, '-rtsp_transport tcp -f rtsp {output}')}"
|
||||
ffmpeg_cmd = f"exec:{parse_preset_hardware_acceleration_encode(ffmpeg_path, config.get('ffmpeg', {}).get('hwaccel_args', ''), input, '-rtsp_transport tcp -f rtsp {output}')}"
|
||||
|
||||
if go2rtc_config.get("streams"):
|
||||
go2rtc_config["streams"]["birdseye"] = ffmpeg_cmd
|
||||
|
||||
@@ -10,8 +10,8 @@ ARG DEBIAN_FRONTEND
|
||||
# Use a separate container to build wheels to prevent build dependencies in final image
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install -y --no-install-recommends \
|
||||
python3.9 python3.9-dev \
|
||||
wget build-essential cmake git \
|
||||
python3.9 python3.9-dev \
|
||||
wget build-essential cmake git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Ensure python3 defaults to python3.9
|
||||
@@ -41,7 +41,11 @@ RUN --mount=type=bind,source=docker/tensorrt/detector/build_python_tensorrt.sh,t
|
||||
&& TENSORRT_VER=$(cat /etc/TENSORRT_VER) /deps/build_python_tensorrt.sh
|
||||
|
||||
COPY docker/tensorrt/requirements-arm64.txt /requirements-tensorrt.txt
|
||||
RUN pip3 wheel --wheel-dir=/trt-wheels -r /requirements-tensorrt.txt
|
||||
ADD https://nvidia.box.com/shared/static/9aemm4grzbbkfaesg5l7fplgjtmswhj8.whl /tmp/onnxruntime_gpu-1.15.1-cp39-cp39-linux_aarch64.whl
|
||||
|
||||
RUN pip3 uninstall -y onnxruntime-openvino \
|
||||
&& pip3 wheel --wheel-dir=/trt-wheels -r /requirements-tensorrt.txt \
|
||||
&& pip3 install --no-deps /tmp/onnxruntime_gpu-1.15.1-cp39-cp39-linux_aarch64.whl
|
||||
|
||||
FROM build-wheels AS trt-model-wheels
|
||||
ARG DEBIAN_FRONTEND
|
||||
|
||||
@@ -25,7 +25,7 @@ ENV S6_CMD_WAIT_FOR_SERVICES_MAXTIME=0
|
||||
COPY --from=trt-deps /usr/local/lib/libyolo_layer.so /usr/local/lib/libyolo_layer.so
|
||||
COPY --from=trt-deps /usr/local/src/tensorrt_demos /usr/local/src/tensorrt_demos
|
||||
COPY docker/tensorrt/detector/rootfs/ /
|
||||
ENV YOLO_MODELS="yolov7-320"
|
||||
ENV YOLO_MODELS=""
|
||||
|
||||
HEALTHCHECK --start-period=600s --start-interval=5s --interval=15s --timeout=5s --retries=3 \
|
||||
CMD curl --fail --silent --show-error http://127.0.0.1:5000/api/version || exit 1
|
||||
|
||||
@@ -11,6 +11,7 @@ set -o errexit -o nounset -o pipefail
|
||||
MODEL_CACHE_DIR=${MODEL_CACHE_DIR:-"/config/model_cache/tensorrt"}
|
||||
TRT_VER=${TRT_VER:-$(cat /etc/TENSORRT_VER)}
|
||||
OUTPUT_FOLDER="${MODEL_CACHE_DIR}/${TRT_VER}"
|
||||
YOLO_MODELS=${YOLO_MODELS:-""}
|
||||
|
||||
# Create output folder
|
||||
mkdir -p ${OUTPUT_FOLDER}
|
||||
@@ -19,6 +20,11 @@ FIRST_MODEL=true
|
||||
MODEL_DOWNLOAD=""
|
||||
MODEL_CONVERT=""
|
||||
|
||||
if [ -z "$YOLO_MODELS"]; then
|
||||
echo "tensorrt model preparation disabled"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for model in ${YOLO_MODELS//,/ }
|
||||
do
|
||||
# Remove old link in case path/version changed
|
||||
|
||||
@@ -9,6 +9,6 @@ nvidia-cuda-runtime-cu11 == 11.8.*; platform_machine == 'x86_64'
|
||||
nvidia-cublas-cu11 == 11.11.3.6; platform_machine == 'x86_64'
|
||||
nvidia-cudnn-cu11 == 8.6.0.*; platform_machine == 'x86_64'
|
||||
nvidia-cufft-cu11==10.*; platform_machine == 'x86_64'
|
||||
onnx==1.14.0; platform_machine == 'x86_64'
|
||||
onnxruntime-gpu==1.17.*; platform_machine == 'x86_64'
|
||||
onnx==1.16.*; platform_machine == 'x86_64'
|
||||
onnxruntime-gpu==1.18.*; platform_machine == 'x86_64'
|
||||
protobuf==3.20.3; platform_machine == 'x86_64'
|
||||
|
||||
@@ -1 +1 @@
|
||||
cuda-python == 11.7; platform_machine == 'aarch64'
|
||||
cuda-python == 11.7; platform_machine == 'aarch64'
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ go2rtc:
|
||||
- rtspx://192.168.1.1:7441/abcdefghijk
|
||||
```
|
||||
|
||||
[See the go2rtc docs for more information](https://github.com/AlexxIT/go2rtc/tree/v1.9.4#source-rtsp)
|
||||
[See the go2rtc docs for more information](https://github.com/AlexxIT/go2rtc/tree/v1.9.2#source-rtsp)
|
||||
|
||||
In the Unifi 2.0 update Unifi Protect Cameras had a change in audio sample rate which causes issues for ffmpeg. The input rate needs to be set for record if used directly with unifi protect.
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ This list of working and non-working PTZ cameras is based on user feedback.
|
||||
| Reolink E1 Zoom | ✅ | ❌ | |
|
||||
| Reolink RLC-823A 16x | ✅ | ❌ | |
|
||||
| Speco O8P32X | ✅ | ❌ | |
|
||||
| Sunba 405-D20X | ✅ | ❌ | |
|
||||
| Sunba 405-D20X | ✅ | ❌ | Incomplete ONVIF support reported on original, and 4k models. All models are suspected incompatable. |
|
||||
| Tapo | ✅ | ❌ | Many models supported, ONVIF Service Port: 2020 |
|
||||
| Uniview IPC672LR-AX4DUPK | ✅ | ❌ | Firmware says FOV relative movement is supported, but camera doesn't actually move when sending ONVIF commands |
|
||||
| Uniview IPC6612SR-X33-VG | ✅ | ✅ | Leave `calibrate_on_startup` as `False`. A user has reported that zooming with `absolute` is working. |
|
||||
|
||||
@@ -3,9 +3,13 @@ id: genai
|
||||
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.
|
||||
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.
|
||||
|
||||
Semantic Search must be enabled to use Generative AI. Descriptions are accessed via the _Explore_ view in the Frigate UI by clicking on a tracked object's thumbnail.
|
||||
:::info
|
||||
|
||||
Semantic Search must be enabled to use Generative AI.
|
||||
|
||||
:::
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -29,15 +33,21 @@ cameras:
|
||||
|
||||
## Ollama
|
||||
|
||||
[Ollama](https://ollama.com/) allows you to self-host large language models and keep everything running locally. It provides a nice API over [llama.cpp](https://github.com/ggerganov/llama.cpp). It is highly recommended to host this server on a machine with an Nvidia graphics card, or on a Apple silicon Mac for best performance. CPU inference is not recommended.
|
||||
:::warning
|
||||
|
||||
Most of the 7b parameter 4-bit vision models will fit inside 8GB of VRAM. There is also a [docker container](https://hub.docker.com/r/ollama/ollama) available.
|
||||
Using Ollama on CPU is not recommended, high inference times make using Generative AI impractical.
|
||||
|
||||
Parallel requests also come with some caveats. See the [Ollama documentation](https://github.com/ollama/ollama/blob/main/docs/faq.md#how-does-ollama-handle-concurrent-requests).
|
||||
:::
|
||||
|
||||
[Ollama](https://ollama.com/) allows you to self-host large language models and keep everything running locally. It provides a nice API over [llama.cpp](https://github.com/ggerganov/llama.cpp). It is highly recommended to host this server on a machine with an Nvidia graphics card, or on a Apple silicon Mac for best performance.
|
||||
|
||||
Most of the 7b parameter 4-bit vision models will fit inside 8GB of VRAM. There is also a [Docker container](https://hub.docker.com/r/ollama/ollama) available.
|
||||
|
||||
Parallel requests also come with some caveats. You will need to set `OLLAMA_NUM_PARALLEL=1` and choose a `OLLAMA_MAX_QUEUE` and `OLLAMA_MAX_LOADED_MODELS` values that are appropriate for your hardware and preferences. See the [Ollama documentation](https://github.com/ollama/ollama/blob/main/docs/faq.md#how-does-ollama-handle-concurrent-requests).
|
||||
|
||||
### Supported Models
|
||||
|
||||
You must use a vision capable model with Frigate. Current model variants can be found [in their model library](https://ollama.com/library). At the time of writing, this includes `llava`, `llava-llama3`, `llava-phi3`, and `moondream`. Note that Frigate will not automatically download the model you specify in your config, you must download the model to your local instance of Ollama first.
|
||||
You must use a vision capable model with Frigate. Current model variants can be found [in their model library](https://ollama.com/library). At the time of writing, this includes `llava`, `llava-llama3`, `llava-phi3`, and `moondream`. Note that Frigate will not automatically download the model you specify in your config, you must download the model to your local instance of Ollama first i.e. by running `ollama pull llava:7b` on your Ollama server/Docker container. Note that the model specified in Frigate's config must match the downloaded model tag.
|
||||
|
||||
:::note
|
||||
|
||||
@@ -52,7 +62,7 @@ genai:
|
||||
enabled: True
|
||||
provider: ollama
|
||||
base_url: http://localhost:11434
|
||||
model: llava
|
||||
model: llava:7b
|
||||
```
|
||||
|
||||
## Google Gemini
|
||||
@@ -132,6 +142,10 @@ Frigate's thumbnail search excels at identifying specific details about tracked
|
||||
|
||||
While generating simple descriptions of detected objects is useful, understanding intent provides a deeper layer of insight. Instead of just recognizing "what" is in a scene, Frigate’s default prompts aim to infer "why" it might be there or "what" it could do next. Descriptions tell you what’s happening, but intent gives context. For instance, a person walking toward a door might seem like a visitor, but if they’re moving quickly after hours, you can infer a potential break-in attempt. Detecting a person loitering near a door at night can trigger an alert sooner than simply noting "a person standing by the door," helping you respond based on the situation’s context.
|
||||
|
||||
### Using GenAI for notifications
|
||||
|
||||
Frigate provides an [MQTT topic](/integrations/mqtt), `frigate/tracked_object_update`, that is updated with a JSON payload containing `event_id` and `description` when your AI provider returns a description for a tracked object. This description could be used directly in notifications, such as sending alerts to your phone or making audio announcements. If additional details from the tracked object are needed, you can query the [HTTP API](/integrations/api/event-events-event-id-get) using the `event_id`, eg: `http://frigate_ip:5000/api/events/<event_id>`.
|
||||
|
||||
## Custom Prompts
|
||||
|
||||
Frigate sends multiple frames from the tracked object along with a prompt to your Generative AI provider asking it to generate a description. The default prompt is as follows:
|
||||
@@ -162,7 +176,7 @@ genai:
|
||||
|
||||
Prompts can also be overriden at the camera level to provide a more detailed prompt to the model about your specific camera, if you desire. By default, descriptions will be generated for all tracked objects and all zones. But you can also optionally specify `objects` and `required_zones` to only generate descriptions for certain tracked objects or zones.
|
||||
|
||||
Optionally, you can generate the description using a snapshot (if enabled) by setting `use_snapshot` to `True`. By default, this is set to `False`, which sends the thumbnails collected over the object's lifetime to the model. Using a snapshot provides the AI with a higher-resolution image (typically downscaled by the AI itself), but the trade-off is that only a single image is used, which might limit the model's ability to determine object movement or direction.
|
||||
Optionally, you can generate the description using a snapshot (if enabled) by setting `use_snapshot` to `True`. By default, this is set to `False`, which sends the uncompressed images from the `detect` stream collected over the object's lifetime to the model. Once the object lifecycle ends, only a single compressed and cropped thumbnail is saved with the tracked object. Using a snapshot might be useful when you want to _regenerate_ a tracked object's description as it will provide the AI with a higher-quality image (typically downscaled by the AI itself) than the cropped/compressed thumbnail. Using a snapshot otherwise has a trade-off in that only a single image is sent to your provider, which will limit the model's ability to determine object movement or direction.
|
||||
|
||||
```yaml
|
||||
cameras:
|
||||
|
||||
@@ -231,28 +231,11 @@ docker run -d \
|
||||
|
||||
### Setup Decoder
|
||||
|
||||
The decoder you need to pass in the `hwaccel_args` will depend on the input video.
|
||||
|
||||
A list of supported codecs (you can use `ffmpeg -decoders | grep cuvid` in the container to get the ones your card supports)
|
||||
|
||||
```
|
||||
V..... h263_cuvid Nvidia CUVID H263 decoder (codec h263)
|
||||
V..... h264_cuvid Nvidia CUVID H264 decoder (codec h264)
|
||||
V..... hevc_cuvid Nvidia CUVID HEVC decoder (codec hevc)
|
||||
V..... mjpeg_cuvid Nvidia CUVID MJPEG decoder (codec mjpeg)
|
||||
V..... mpeg1_cuvid Nvidia CUVID MPEG1VIDEO decoder (codec mpeg1video)
|
||||
V..... mpeg2_cuvid Nvidia CUVID MPEG2VIDEO decoder (codec mpeg2video)
|
||||
V..... mpeg4_cuvid Nvidia CUVID MPEG4 decoder (codec mpeg4)
|
||||
V..... vc1_cuvid Nvidia CUVID VC1 decoder (codec vc1)
|
||||
V..... vp8_cuvid Nvidia CUVID VP8 decoder (codec vp8)
|
||||
V..... vp9_cuvid Nvidia CUVID VP9 decoder (codec vp9)
|
||||
```
|
||||
|
||||
For example, for H264 video, you'll select `preset-nvidia-h264`.
|
||||
Using `preset-nvidia` ffmpeg will automatically select the necessary profile for the incoming video, and will log an error if the profile is not supported by your GPU.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: preset-nvidia-h264
|
||||
hwaccel_args: preset-nvidia
|
||||
```
|
||||
|
||||
If everything is working correctly, you should see a significant improvement in performance.
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -92,10 +92,16 @@ motion:
|
||||
lightning_threshold: 0.8
|
||||
```
|
||||
|
||||
:::tip
|
||||
:::warning
|
||||
|
||||
Some cameras like doorbell cameras may have missed detections when someone walks directly in front of the camera and the lightning_threshold causes motion detection to be re-calibrated. In this case, it may be desirable to increase the `lightning_threshold` to ensure these objects are not missed.
|
||||
|
||||
:::
|
||||
|
||||
:::note
|
||||
|
||||
Lightning threshold does not stop motion based recordings from being saved.
|
||||
|
||||
:::
|
||||
|
||||
Large changes in motion like PTZ moves and camera switches between Color and IR mode should result in no motion detection. This is done via the `lightning_threshold` configuration. It is defined as the percentage of the image used to detect lightning or other substantial changes where motion detection needs to recalibrate. Increasing this value will make motion detection more likely to consider lightning or IR mode changes as valid motion. Decreasing this value will make motion detection more likely to ignore large amounts of motion such as a person approaching a doorbell camera.
|
||||
|
||||
@@ -22,14 +22,14 @@ Frigate supports multiple different detectors that work on different types of ha
|
||||
- [ONNX](#onnx): OpenVINO will automatically be detected and used as a detector in the default Frigate image when a supported ONNX model is configured.
|
||||
|
||||
**Nvidia**
|
||||
- [TensortRT](#nvidia-tensorrt-detector): TensorRT can run on Nvidia GPUs, using one of many default models.
|
||||
- [ONNX](#onnx): TensorRT will automatically be detected and used as a detector in the `-tensorrt` Frigate image when a supported ONNX model is configured.
|
||||
- [TensortRT](#nvidia-tensorrt-detector): TensorRT can run on Nvidia GPUs and Jetson devices, using one of many default models.
|
||||
- [ONNX](#onnx): TensorRT will automatically be detected and used as a detector in the `-tensorrt` or `-tensorrt-jp(4/5)` Frigate images when a supported ONNX model is configured.
|
||||
|
||||
**Rockchip**
|
||||
- [RKNN](#rockchip-platform): RKNN models can run on Rockchip devices with included NPUs.
|
||||
|
||||
**For Testing**
|
||||
- [CPU Detector (not recommended for actual use](#cpu-detector-not-recommended): Use a CPU to run tflite model, this is not recommended and in most cases OpenVINO can be used in CPU mode with better results.
|
||||
- [CPU Detector (not recommended for actual use](#cpu-detector-not-recommended): Use a CPU to run tflite model, this is not recommended and in most cases OpenVINO can be used in CPU mode with better results.
|
||||
|
||||
:::
|
||||
|
||||
@@ -223,7 +223,7 @@ The model used for TensorRT must be preprocessed on the same hardware platform t
|
||||
|
||||
The Frigate image will generate model files during startup if the specified model is not found. Processed models are stored in the `/config/model_cache` folder. Typically the `/config` path is mapped to a directory on the host already and the `model_cache` does not need to be mapped separately unless the user wants to store it in a different location on the host.
|
||||
|
||||
By default, the `yolov7-320` model will be generated, but this can be overridden by specifying the `YOLO_MODELS` environment variable in Docker. One or more models may be listed in a comma-separated format, and each one will be generated. To select no model generation, set the variable to an empty string, `YOLO_MODELS=""`. Models will only be generated if the corresponding `{model}.trt` file is not present in the `model_cache` folder, so you can force a model to be regenerated by deleting it from your Frigate data folder.
|
||||
By default, no models will be generated, but this can be overridden by specifying the `YOLO_MODELS` environment variable in Docker. One or more models may be listed in a comma-separated format, and each one will be generated. Models will only be generated if the corresponding `{model}.trt` file is not present in the `model_cache` folder, so you can force a model to be regenerated by deleting it from your Frigate data folder.
|
||||
|
||||
If you have a Jetson device with DLAs (Xavier or Orin), you can generate a model that will run on the DLA by appending `-dla` to your model name, e.g. specify `YOLO_MODELS=yolov7-320-dla`. The model will run on DLA0 (Frigate does not currently support DLA1). DLA-incompatible layers will fall back to running on the GPU.
|
||||
|
||||
@@ -264,7 +264,7 @@ An example `docker-compose.yml` fragment that converts the `yolov4-608` and `yol
|
||||
```yml
|
||||
frigate:
|
||||
environment:
|
||||
- YOLO_MODELS=yolov4-608,yolov7x-640
|
||||
- YOLO_MODELS=yolov7-320,yolov7x-640
|
||||
- USE_FP16=false
|
||||
```
|
||||
|
||||
@@ -415,6 +415,24 @@ Note that the labelmap uses a subset of the complete COCO label set that has onl
|
||||
|
||||
ONNX is an open format for building machine learning models, Frigate supports running ONNX models on CPU, OpenVINO, and TensorRT. On startup Frigate will automatically try to use a GPU if one is available.
|
||||
|
||||
:::info
|
||||
|
||||
If the correct build is used for your GPU then the GPU will be detected and used automatically.
|
||||
|
||||
- **AMD**
|
||||
|
||||
- ROCm will automatically be detected and used with the ONNX detector in the `-rocm` Frigate image.
|
||||
|
||||
- **Intel**
|
||||
|
||||
- OpenVINO will automatically be detected and used with the ONNX detector in the default Frigate image.
|
||||
|
||||
- **Nvidia**
|
||||
- Nvidia GPUs will automatically be detected and used with the ONNX detector in the `-tensorrt` Frigate image.
|
||||
- Jetson devices will automatically be detected and used with the ONNX detector in the `-tensorrt-jp(4/5)` Frigate image.
|
||||
|
||||
:::
|
||||
|
||||
:::tip
|
||||
|
||||
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be:
|
||||
@@ -457,6 +475,7 @@ model:
|
||||
width: 320 # <--- should match whatever was set in notebook
|
||||
height: 320 # <--- should match whatever was set in notebook
|
||||
input_pixel_format: bgr
|
||||
input_tensor: nchw
|
||||
path: /config/yolo_nas_s.onnx
|
||||
labelmap_path: /labelmap/coco-80.txt
|
||||
```
|
||||
|
||||
@@ -5,7 +5,7 @@ title: Available Objects
|
||||
|
||||
import labels from "../../../labelmap.txt";
|
||||
|
||||
Frigate includes the object models listed below from the Google Coral test data.
|
||||
Frigate includes the object labels listed below from the Google Coral test data.
|
||||
|
||||
Please note:
|
||||
|
||||
|
||||
@@ -548,10 +548,12 @@ genai:
|
||||
# Uses https://github.com/AlexxIT/go2rtc (v1.9.2)
|
||||
go2rtc:
|
||||
|
||||
# Optional: jsmpeg stream configuration for WebUI
|
||||
# Optional: Live stream configuration for WebUI.
|
||||
# NOTE: Can be overridden at the camera level
|
||||
live:
|
||||
# Optional: Set the name of the stream that should be used for live view
|
||||
# in frigate WebUI. (default: name of camera)
|
||||
# Optional: Set the name of the stream configured in go2rtc
|
||||
# that should be used for live view in frigate WebUI. (default: name of camera)
|
||||
# NOTE: In most cases this should be set at the camera level only.
|
||||
stream_name: camera_name
|
||||
# Optional: Set the height of the jsmpeg stream. (default: 720)
|
||||
# This must be less than or equal to the height of the detect stream. Lower resolutions
|
||||
|
||||
@@ -7,7 +7,7 @@ title: Restream
|
||||
|
||||
Frigate can restream your video feed as an RTSP feed for other applications such as Home Assistant to utilize it at `rtsp://<frigate_host>:8554/<camera_name>`. Port 8554 must be open. [This allows you to use a video feed for detection in Frigate and Home Assistant live view at the same time without having to make two separate connections to the camera](#reduce-connections-to-camera). The video feed is copied from the original video feed directly to avoid re-encoding. This feed does not include any annotation by Frigate.
|
||||
|
||||
Frigate uses [go2rtc](https://github.com/AlexxIT/go2rtc/tree/v1.9.4) to provide its restream and MSE/WebRTC capabilities. The go2rtc config is hosted at the `go2rtc` in the config, see [go2rtc docs](https://github.com/AlexxIT/go2rtc/tree/v1.9.4#configuration) for more advanced configurations and features.
|
||||
Frigate uses [go2rtc](https://github.com/AlexxIT/go2rtc/tree/v1.9.2) to provide its restream and MSE/WebRTC capabilities. The go2rtc config is hosted at the `go2rtc` in the config, see [go2rtc docs](https://github.com/AlexxIT/go2rtc/tree/v1.9.2#configuration) for more advanced configurations and features.
|
||||
|
||||
:::note
|
||||
|
||||
@@ -132,9 +132,31 @@ cameras:
|
||||
- detect
|
||||
```
|
||||
|
||||
## Handling Complex Passwords
|
||||
|
||||
go2rtc expects URL-encoded passwords in the config, [urlencoder.org](https://urlencoder.org) can be used for this purpose.
|
||||
|
||||
For example:
|
||||
|
||||
```yaml
|
||||
go2rtc:
|
||||
streams:
|
||||
my_camera: rtsp://username:$@foo%@192.168.1.100
|
||||
```
|
||||
|
||||
becomes
|
||||
|
||||
```yaml
|
||||
go2rtc:
|
||||
streams:
|
||||
my_camera: rtsp://username:$%40foo%25@192.168.1.100
|
||||
```
|
||||
|
||||
See [this comment(https://github.com/AlexxIT/go2rtc/issues/1217#issuecomment-2242296489) for more information.
|
||||
|
||||
## Advanced Restream Configurations
|
||||
|
||||
The [exec](https://github.com/AlexxIT/go2rtc/tree/v1.9.4#source-exec) source in go2rtc can be used for custom ffmpeg commands. An example is below:
|
||||
The [exec](https://github.com/AlexxIT/go2rtc/tree/v1.9.2#source-exec) source in go2rtc can be used for custom ffmpeg commands. An example is below:
|
||||
|
||||
NOTE: The output will need to be passed with two curly braces `{{output}}`
|
||||
|
||||
|
||||
@@ -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,15 +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:
|
||||
|
||||
:::tip
|
||||
|
||||
The CLIP models are downloaded in ONNX format, which means they will be accelerated using GPU hardware when available. This depends on the Docker build that is used. See [the object detector docs](../configuration/object_detectors.md) for more information.
|
||||
|
||||
:::
|
||||
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:
|
||||
@@ -56,11 +50,41 @@ 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 much less RAM and runs faster 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
|
||||
|
||||
The CLIP models are downloaded in ONNX format, and the `large` model can be accelerated using GPU hardware, when available. This depends on the Docker build that is used.
|
||||
|
||||
```yaml
|
||||
semantic_search:
|
||||
enabled: True
|
||||
model_size: large
|
||||
```
|
||||
|
||||
:::info
|
||||
|
||||
If the correct build is used for your GPU and the `large` model is configured, then the GPU will be detected and used automatically.
|
||||
|
||||
**NOTE:** Object detection and Semantic Search are independent features. If you want to use your GPU with Semantic Search, you must choose the appropriate Frigate Docker image for your GPU.
|
||||
|
||||
- **AMD**
|
||||
|
||||
- ROCm will automatically be detected and used for Semantic Search in the `-rocm` Frigate image.
|
||||
|
||||
- **Intel**
|
||||
|
||||
- OpenVINO will automatically be detected and used for Semantic Search in the default Frigate image.
|
||||
|
||||
- **Nvidia**
|
||||
- Nvidia GPUs will automatically be detected and used for Semantic Search in the `-tensorrt` Frigate image.
|
||||
- Jetson devices will automatically be detected and used for Semantic Search in the `-tensorrt-jp(4/5)` Frigate image.
|
||||
|
||||
:::
|
||||
|
||||
## 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".
|
||||
|
||||
@@ -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)**
|
||||
|
||||
|
||||
@@ -81,15 +81,15 @@ You can calculate the **minimum** shm size for each camera with the following fo
|
||||
|
||||
```console
|
||||
# Replace <width> and <height>
|
||||
$ python -c 'print("{:.2f}MB".format((<width> * <height> * 1.5 * 10 + 270480) / 1048576))'
|
||||
$ python -c 'print("{:.2f}MB".format((<width> * <height> * 1.5 * 20 + 270480) / 1048576))'
|
||||
|
||||
# Example for 1280x720
|
||||
$ python -c 'print("{:.2f}MB".format((1280 * 720 * 1.5 * 10 + 270480) / 1048576))'
|
||||
13.44MB
|
||||
# Example for 1280x720, including logs
|
||||
$ python -c 'print("{:.2f}MB".format((1280 * 720 * 1.5 * 20 + 270480) / 1048576)) + 40'
|
||||
46.63MB
|
||||
|
||||
# Example for eight cameras detecting at 1280x720, including logs
|
||||
$ python -c 'print("{:.2f}MB".format(((1280 * 720 * 1.5 * 10 + 270480) / 1048576) * 8 + 40))'
|
||||
136.99MB
|
||||
$ python -c 'print("{:.2f}MB".format(((1280 * 720 * 1.5 * 20 + 270480) / 1048576) * 8 + 40))'
|
||||
253MB
|
||||
```
|
||||
|
||||
The shm size cannot be set per container for Home Assistant add-ons. However, this is probably not required since by default Home Assistant Supervisor allocates `/dev/shm` with half the size of your total memory. If your machine has 8GB of memory, chances are that Frigate will have access to up to 4GB without any additional configuration.
|
||||
@@ -193,8 +193,9 @@ services:
|
||||
container_name: frigate
|
||||
privileged: true # this may not be necessary for all setups
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 30s # allow enough time to shut down the various services
|
||||
image: ghcr.io/blakeblackshear/frigate:stable
|
||||
shm_size: "64mb" # update for your cameras based on calculation above
|
||||
shm_size: "512mb" # update for your cameras based on calculation above
|
||||
devices:
|
||||
- /dev/bus/usb:/dev/bus/usb # Passes the USB Coral, needs to be modified for other versions
|
||||
- /dev/apex_0:/dev/apex_0 # Passes a PCIe Coral, follow driver instructions here https://coral.ai/docs/m2/get-started/#2a-on-linux
|
||||
@@ -224,6 +225,7 @@ If you can't use docker compose, you can run the container with something simila
|
||||
docker run -d \
|
||||
--name frigate \
|
||||
--restart=unless-stopped \
|
||||
--stop-timeout 30 \
|
||||
--mount type=tmpfs,target=/tmp/cache,tmpfs-size=1000000000 \
|
||||
--device /dev/bus/usb:/dev/bus/usb \
|
||||
--device /dev/dri/renderD128 \
|
||||
|
||||
@@ -13,7 +13,15 @@ Use of the bundled go2rtc is optional. You can still configure FFmpeg to connect
|
||||
|
||||
# Setup a go2rtc stream
|
||||
|
||||
First, you will want to configure go2rtc to connect to your camera stream by adding the stream you want to use for live view in your Frigate config file. For the best experience, you should set the stream name under go2rtc to match the name of your camera so that Frigate will automatically map it and be able to use better live view options for the camera. Avoid changing any other parts of your config at this step. Note that go2rtc supports [many different stream types](https://github.com/AlexxIT/go2rtc/tree/v1.9.4#module-streams), not just rtsp.
|
||||
First, you will want to configure go2rtc to connect to your camera stream by adding the stream you want to use for live view in your Frigate config file. Avoid changing any other parts of your config at this step. Note that go2rtc supports [many different stream types](https://github.com/AlexxIT/go2rtc/tree/v1.9.2#module-streams), not just rtsp.
|
||||
|
||||
:::tip
|
||||
|
||||
For the best experience, you should set the stream name under `go2rtc` to match the name of your camera so that Frigate will automatically map it and be able to use better live view options for the camera.
|
||||
|
||||
See [the live view docs](../configuration/live.md#setting-stream-for-live-ui) for more information.
|
||||
|
||||
:::
|
||||
|
||||
```yaml
|
||||
go2rtc:
|
||||
@@ -39,8 +47,8 @@ After adding this to the config, restart Frigate and try to watch the live strea
|
||||
|
||||
- Check Video Codec:
|
||||
- If the camera stream works in go2rtc but not in your browser, the video codec might be unsupported.
|
||||
- If using H265, switch to H264. Refer to [video codec compatibility](https://github.com/AlexxIT/go2rtc/tree/v1.9.4#codecs-madness) in go2rtc documentation.
|
||||
- If unable to switch from H265 to H264, or if the stream format is different (e.g., MJPEG), re-encode the video using [FFmpeg parameters](https://github.com/AlexxIT/go2rtc/tree/v1.9.4#source-ffmpeg). It supports rotating and resizing video feeds and hardware acceleration. Keep in mind that transcoding video from one format to another is a resource intensive task and you may be better off using the built-in jsmpeg view.
|
||||
- If using H265, switch to H264. Refer to [video codec compatibility](https://github.com/AlexxIT/go2rtc/tree/v1.9.2#codecs-madness) in go2rtc documentation.
|
||||
- If unable to switch from H265 to H264, or if the stream format is different (e.g., MJPEG), re-encode the video using [FFmpeg parameters](https://github.com/AlexxIT/go2rtc/tree/v1.9.2#source-ffmpeg). It supports rotating and resizing video feeds and hardware acceleration. Keep in mind that transcoding video from one format to another is a resource intensive task and you may be better off using the built-in jsmpeg view.
|
||||
```yaml
|
||||
go2rtc:
|
||||
streams:
|
||||
|
||||
@@ -115,6 +115,7 @@ services:
|
||||
frigate:
|
||||
container_name: frigate
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 30s
|
||||
image: ghcr.io/blakeblackshear/frigate:stable
|
||||
volumes:
|
||||
- ./config:/config
|
||||
@@ -306,7 +307,9 @@ By default, Frigate will retain video of all tracked objects for 10 days. The fu
|
||||
|
||||
### Step 7: Complete config
|
||||
|
||||
At this point you have a complete config with basic functionality. You can see the [full config reference](../configuration/reference.md) for a complete list of configuration options.
|
||||
At this point you have a complete config with basic functionality.
|
||||
- View [common configuration examples](../configuration/index.md#common-configuration-examples) for a list of common configuration examples.
|
||||
- View [full config reference](../configuration/reference.md) for a complete list of configuration options.
|
||||
|
||||
### Follow up
|
||||
|
||||
|
||||
@@ -94,6 +94,18 @@ Message published for each changed tracked object. The first message is publishe
|
||||
}
|
||||
```
|
||||
|
||||
### `frigate/tracked_object_update`
|
||||
|
||||
Message published for updates to tracked object metadata, for example when GenAI runs and returns a tracked object description.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "description",
|
||||
"id": "1607123955.475377-mxklsc",
|
||||
"description": "The car is a red sedan moving away from the camera."
|
||||
}
|
||||
```
|
||||
|
||||
### `frigate/reviews`
|
||||
|
||||
Message published for each changed review item. The first message is published when the `detection` or `alert` is initiated. When additional objects are detected or when a zone change occurs, it will publish a, `update` message with the same id. When the review activity has ended a final `end` message is published.
|
||||
|
||||
@@ -5,7 +5,7 @@ title: Requesting your first model
|
||||
|
||||
## Step 1: Upload and annotate your images
|
||||
|
||||
Before requesting your first model, you will need to upload at least 10 images to Frigate+. But for the best results, you should provide at least 100 verified images per camera. Keep in mind that varying conditions should be included. You will want images from cloudy days, sunny days, dawn, dusk, and night. Refer to the [integration docs](../integrations/plus.md#generate-an-api-key) for instructions on how to easily submit images to Frigate+ directly from Frigate.
|
||||
Before requesting your first model, you will need to upload and verify at least 1 image to Frigate+. The more images you upload, annotate, and verify the better your results will be. Most users start to see very good results once they have at least 100 verified images per camera. Keep in mind that varying conditions should be included. You will want images from cloudy days, sunny days, dawn, dusk, and night. Refer to the [integration docs](../integrations/plus.md#generate-an-api-key) for instructions on how to easily submit images to Frigate+ directly from Frigate.
|
||||
|
||||
It is recommended to submit **both** true positives and false positives. This will help the model differentiate between what is and isn't correct. You should aim for a target of 80% true positive submissions and 20% false positives across all of your images. If you are experiencing false positives in a specific area, submitting true positives for any object type near that area in similar lighting conditions will help teach the model what that area looks like when no objects are present.
|
||||
|
||||
@@ -13,7 +13,7 @@ For more detailed recommendations, you can refer to the docs on [improving your
|
||||
|
||||
## Step 2: Submit a model request
|
||||
|
||||
Once you have an initial set of verified images, you can request a model on the Models page. Each model request requires 1 of the 12 trainings that you receive with your annual subscription. This model will support all [label types available](./index.md#available-label-types) even if you do not submit any examples for those labels. Model creation can take up to 36 hours.
|
||||
Once you have an initial set of verified images, you can request a model on the Models page. For guidance on choosing a model type, refer to [this part of the documentation](./index.md#available-model-types). Each model request requires 1 of the 12 trainings that you receive with your annual subscription. This model will support all [label types available](./index.md#available-label-types) even if you do not submit any examples for those labels. Model creation can take up to 36 hours.
|
||||

|
||||
|
||||
## Step 3: Set your model id in the config
|
||||
|
||||
@@ -3,7 +3,7 @@ id: improving_model
|
||||
title: Improving your model
|
||||
---
|
||||
|
||||
You may find that Frigate+ models result in more false positives initially, but by submitting true and false positives, the model will improve. Because a limited number of users submitted images to Frigate+ prior to this launch, you may need to submit several hundred images per camera to see good results. With all the new images now being submitted, future base models will improve as more and more users (including you) submit examples to Frigate+. Note that only verified images will be used when training your model. Submitting an image from Frigate as a true or false positive will not verify the image. You still must verify the image in Frigate+ in order for it to be used in training.
|
||||
You may find that Frigate+ models result in more false positives initially, but by submitting true and false positives, the model will improve. With all the new images now being submitted by subscribers, future base models will improve as more and more examples are incorporated. Note that only images with at least one verified label will be used when training your model. Submitting an image from Frigate as a true or false positive will not verify the image. You still must verify the image in Frigate+ in order for it to be used in training.
|
||||
|
||||
- **Submit both true positives and false positives**. This will help the model differentiate between what is and isn't correct. You should aim for a target of 80% true positive submissions and 20% false positives across all of your images. If you are experiencing false positives in a specific area, submitting true positives for any object type near that area in similar lighting conditions will help teach the model what that area looks like when no objects are present.
|
||||
- **Lower your thresholds a little in order to generate more false/true positives near the threshold value**. For example, if you have some false positives that are scoring at 68% and some true positives scoring at 72%, you can try lowering your threshold to 65% and submitting both true and false positives within that range. This will help the model learn and widen the gap between true and false positive scores.
|
||||
@@ -36,18 +36,17 @@ Misidentified objects should have a correct label added. For example, if a perso
|
||||
|
||||
## Shortcuts for a faster workflow
|
||||
|
||||
|Shortcut Key|Description|
|
||||
|-----|--------|
|
||||
|`?`|Show all keyboard shortcuts|
|
||||
|`w`|Add box|
|
||||
|`d`|Toggle difficult|
|
||||
|`s`|Switch to the next label|
|
||||
|`tab`|Select next largest box|
|
||||
|`del`|Delete current box|
|
||||
|`esc`|Deselect/Cancel|
|
||||
|`← ↑ → ↓`|Move box|
|
||||
|`Shift + ← ↑ → ↓`|Resize box|
|
||||
|`-`|Zoom out|
|
||||
|`=`|Zoom in|
|
||||
|`f`|Hide/show all but current box|
|
||||
|`spacebar`|Verify and save|
|
||||
| Shortcut Key | Description |
|
||||
| ----------------- | ----------------------------- |
|
||||
| `?` | Show all keyboard shortcuts |
|
||||
| `w` | Add box |
|
||||
| `d` | Toggle difficult |
|
||||
| `s` | Switch to the next label |
|
||||
| `tab` | Select next largest box |
|
||||
| `del` | Delete current box |
|
||||
| `esc` | Deselect/Cancel |
|
||||
| `← ↑ → ↓` | Move box |
|
||||
| `Shift + ← ↑ → ↓` | Resize box |
|
||||
| `scrollwheel` | Zoom in/out |
|
||||
| `f` | Hide/show all but current box |
|
||||
| `spacebar` | Verify and save |
|
||||
|
||||
@@ -15,17 +15,36 @@ With a subscription, 12 model trainings per year are included. If you cancel you
|
||||
|
||||
Information on how to integrate Frigate+ with Frigate can be found in the [integration docs](../integrations/plus.md).
|
||||
|
||||
## Available model types
|
||||
|
||||
There are two model types offered in Frigate+: `mobiledet` and `yolonas`. Both of these models are object detection models and are trained to detect the same set of labels [listed below](#available-label-types).
|
||||
|
||||
Not all model types are supported by all detectors, so it's important to choose a model type to match your detector as shown in the table under [supported detector types](#supported-detector-types).
|
||||
|
||||
| Model Type | Description |
|
||||
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `mobiledet` | Based on the same architecture as the default model included with Frigate. Runs on Google Coral devices and CPUs. |
|
||||
| `yolonas` | A newer architecture that offers slightly higher accuracy and improved detection of small objects. Runs on Intel, NVidia GPUs, and AMD GPUs. |
|
||||
|
||||
## Supported detector types
|
||||
|
||||
Currently, Frigate+ models support CPU (`cpu`), Google Coral (`edgetpu`), OpenVino (`openvino`), ONNX (`onnx`), and ROCm (`rocm`) detectors.
|
||||
|
||||
:::warning
|
||||
|
||||
Frigate+ models are not supported for TensorRT or OpenVino yet.
|
||||
Using Frigate+ models with `onnx` and `rocm` is only available with Frigate 0.15, which is still under development.
|
||||
|
||||
:::
|
||||
|
||||
Currently, Frigate+ models only support CPU (`cpu`) and Coral (`edgetpu`) models. OpenVino is next in line to gain support.
|
||||
| Hardware | Recommended Detector Type | Recommended Model Type |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ---------------------- |
|
||||
| [CPU](/configuration/object_detectors.md#cpu-detector-not-recommended) | `cpu` | `mobiledet` |
|
||||
| [Coral (all form factors)](/configuration/object_detectors.md#edge-tpu-detector) | `edgetpu` | `mobiledet` |
|
||||
| [Intel](/configuration/object_detectors.md#openvino-detector) | `openvino` | `yolonas` |
|
||||
| [NVidia GPU](https://deploy-preview-13787--frigate-docs.netlify.app/configuration/object_detectors#onnx)\* | `onnx` | `yolonas` |
|
||||
| [AMD ROCm GPU](https://deploy-preview-13787--frigate-docs.netlify.app/configuration/object_detectors#amdrocm-gpu-detector)\* | `rocm` | `yolonas` |
|
||||
|
||||
The models are created using the same MobileDet architecture as the default model. Additional architectures will be added in future releases as needed.
|
||||
_\* Requires Frigate 0.15_
|
||||
|
||||
## Available label types
|
||||
|
||||
|
||||
@@ -49,7 +49,10 @@ The USB Coral can become stuck and need to be restarted, this can happen for a n
|
||||
|
||||
## PCIe Coral Not Detected
|
||||
|
||||
The most common reason for the PCIe coral not being detected is that the driver has not been installed. See [the coral docs](https://coral.ai/docs/m2/get-started/#2-install-the-pcie-driver-and-edge-tpu-runtime) for how to install the driver for the PCIe based coral.
|
||||
The most common reason for the PCIe Coral not being detected is that the driver has not been installed. This process varies based on what OS and kernel that is being run.
|
||||
|
||||
- In most cases [the Coral docs](https://coral.ai/docs/m2/get-started/#2-install-the-pcie-driver-and-edge-tpu-runtime) show how to install the driver for the PCIe based Coral.
|
||||
- For Ubuntu 22.04+ https://github.com/jnicolson/gasket-builder can be used to build and install the latest version of the driver.
|
||||
|
||||
## Only One PCIe Coral Is Detected With Coral Dual EdgeTPU
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -26,7 +26,7 @@ const sidebars: SidebarsConfig = {
|
||||
{
|
||||
type: 'link',
|
||||
label: 'Go2RTC Configuration Reference',
|
||||
href: 'https://github.com/AlexxIT/go2rtc/tree/v1.9.4#configuration',
|
||||
href: 'https://github.com/AlexxIT/go2rtc/tree/v1.9.2#configuration',
|
||||
} as PropSidebarItemLink,
|
||||
],
|
||||
Detectors: [
|
||||
|
||||
1621
docs/static/frigate-api.yaml
vendored
1621
docs/static/frigate-api.yaml
vendored
File diff suppressed because it is too large
Load Diff
@@ -17,17 +17,17 @@ from fastapi.responses import JSONResponse, PlainTextResponse
|
||||
from markupsafe import escape
|
||||
from peewee import operator
|
||||
|
||||
from frigate.api.defs.app_body import AppConfigSetBody
|
||||
from frigate.api.defs.app_query_parameters import AppTimelineHourlyQueryParameters
|
||||
from frigate.api.defs.query.app_query_parameters import AppTimelineHourlyQueryParameters
|
||||
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,
|
||||
@@ -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
|
||||
@@ -147,13 +163,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 +208,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 +257,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()
|
||||
|
||||
@@ -18,7 +18,7 @@ from joserfc import jwt
|
||||
from peewee import DoesNotExist
|
||||
from slowapi import Limiter
|
||||
|
||||
from frigate.api.defs.app_body import (
|
||||
from frigate.api.defs.request.app_body import (
|
||||
AppPostLoginBody,
|
||||
AppPostUsersBody,
|
||||
AppPutPasswordBody,
|
||||
@@ -85,7 +85,12 @@ def get_remote_addr(request: Request):
|
||||
return str(ip)
|
||||
|
||||
# if there wasn't anything in the route, just return the default
|
||||
return request.remote_addr or "127.0.0.1"
|
||||
remote_addr = None
|
||||
|
||||
if hasattr(request, "remote_addr"):
|
||||
remote_addr = request.remote_addr
|
||||
|
||||
return remote_addr or "127.0.0.1"
|
||||
|
||||
|
||||
def get_jwt_secret() -> str:
|
||||
@@ -324,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):
|
||||
@@ -335,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")
|
||||
|
||||
0
frigate/api/defs/__init__.py
Normal file
0
frigate/api/defs/__init__.py
Normal file
@@ -28,6 +28,7 @@ class EventsQueryParams(BaseModel):
|
||||
is_submitted: Optional[int] = None
|
||||
min_length: Optional[float] = None
|
||||
max_length: Optional[float] = None
|
||||
event_id: Optional[str] = None
|
||||
sort: Optional[str] = None
|
||||
timezone: Optional[str] = "utc"
|
||||
|
||||
@@ -46,6 +47,7 @@ class EventsSearchQueryParams(BaseModel):
|
||||
time_range: Optional[str] = DEFAULT_TIME_RANGE
|
||||
has_clip: Optional[bool] = None
|
||||
has_snapshot: Optional[bool] = None
|
||||
is_submitted: Optional[bool] = None
|
||||
timezone: Optional[str] = "utc"
|
||||
min_score: Optional[float] = None
|
||||
max_score: Optional[float] = None
|
||||
31
frigate/api/defs/query/review_query_parameters.py
Normal file
31
frigate/api/defs/query/review_query_parameters.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from typing import Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic.json_schema import SkipJsonSchema
|
||||
|
||||
from frigate.review.types import SeverityEnum
|
||||
|
||||
|
||||
class ReviewQueryParams(BaseModel):
|
||||
cameras: str = "all"
|
||||
labels: str = "all"
|
||||
zones: str = "all"
|
||||
reviewed: int = 0
|
||||
limit: Union[int, SkipJsonSchema[None]] = None
|
||||
severity: Union[SeverityEnum, SkipJsonSchema[None]] = None
|
||||
before: Union[float, SkipJsonSchema[None]] = None
|
||||
after: Union[float, SkipJsonSchema[None]] = None
|
||||
|
||||
|
||||
class ReviewSummaryQueryParams(BaseModel):
|
||||
cameras: str = "all"
|
||||
labels: str = "all"
|
||||
zones: str = "all"
|
||||
timezone: str = "utc"
|
||||
|
||||
|
||||
class ReviewActivityMotionQueryParams(BaseModel):
|
||||
cameras: str = "all"
|
||||
before: Union[float, SkipJsonSchema[None]] = None
|
||||
after: Union[float, SkipJsonSchema[None]] = None
|
||||
scale: int = 30
|
||||
0
frigate/api/defs/request/__init__.py
Normal file
0
frigate/api/defs/request/__init__.py
Normal file
@@ -1,4 +1,4 @@
|
||||
from typing import Optional, Union
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -17,14 +17,18 @@ class EventsDescriptionBody(BaseModel):
|
||||
class EventsCreateBody(BaseModel):
|
||||
source_type: Optional[str] = "api"
|
||||
sub_label: Optional[str] = None
|
||||
score: Optional[int] = 0
|
||||
score: Optional[float] = 0
|
||||
duration: Optional[int] = 30
|
||||
include_recording: Optional[bool] = True
|
||||
draw: Optional[dict] = {}
|
||||
|
||||
|
||||
class EventsEndBody(BaseModel):
|
||||
end_time: Optional[int] = None
|
||||
end_time: Optional[float] = None
|
||||
|
||||
|
||||
class EventsDeleteBody(BaseModel):
|
||||
event_ids: List[str] = Field(title="The event IDs to delete")
|
||||
|
||||
|
||||
class SubmitPlusBody(BaseModel):
|
||||
20
frigate/api/defs/request/export_recordings_body.py
Normal file
20
frigate/api/defs/request/export_recordings_body.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from typing import Union
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic.json_schema import SkipJsonSchema
|
||||
|
||||
from frigate.record.export import (
|
||||
PlaybackFactorEnum,
|
||||
PlaybackSourceEnum,
|
||||
)
|
||||
|
||||
|
||||
class ExportRecordingsBody(BaseModel):
|
||||
playback: PlaybackFactorEnum = Field(
|
||||
default=PlaybackFactorEnum.realtime, title="Playback factor"
|
||||
)
|
||||
source: PlaybackSourceEnum = Field(
|
||||
default=PlaybackSourceEnum.recordings, title="Playback source"
|
||||
)
|
||||
name: str = Field(title="Friendly name", default=None, max_length=256)
|
||||
image_path: Union[str, SkipJsonSchema[None]] = None
|
||||
6
frigate/api/defs/request/review_body.py
Normal file
6
frigate/api/defs/request/review_body.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, conlist, constr
|
||||
|
||||
|
||||
class ReviewModifyMultipleBody(BaseModel):
|
||||
# List of string with at least one element and each element with at least one char
|
||||
ids: conlist(constr(min_length=1), min_length=1)
|
||||
42
frigate/api/defs/response/event_response.py
Normal file
42
frigate/api/defs/response/event_response.py
Normal file
@@ -0,0 +1,42 @@
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class EventResponse(BaseModel):
|
||||
id: str
|
||||
label: str
|
||||
sub_label: Optional[str]
|
||||
camera: str
|
||||
start_time: float
|
||||
end_time: Optional[float]
|
||||
false_positive: Optional[bool]
|
||||
zones: list[str]
|
||||
thumbnail: str
|
||||
has_clip: bool
|
||||
has_snapshot: bool
|
||||
retain_indefinitely: bool
|
||||
plus_id: Optional[str]
|
||||
model_hash: Optional[str]
|
||||
detector_type: Optional[str]
|
||||
model_type: Optional[str]
|
||||
data: dict[str, Any]
|
||||
|
||||
model_config = ConfigDict(protected_namespaces=())
|
||||
|
||||
|
||||
class EventCreateResponse(BaseModel):
|
||||
success: bool
|
||||
message: str
|
||||
event_id: str
|
||||
|
||||
|
||||
class EventMultiDeleteResponse(BaseModel):
|
||||
success: bool
|
||||
deleted_events: list[str]
|
||||
not_found_events: list[str]
|
||||
|
||||
|
||||
class EventUploadPlusResponse(BaseModel):
|
||||
success: bool
|
||||
plus_id: str
|
||||
6
frigate/api/defs/response/generic_response.py
Normal file
6
frigate/api/defs/response/generic_response.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class GenericResponse(BaseModel):
|
||||
success: bool
|
||||
message: str
|
||||
43
frigate/api/defs/response/review_response.py
Normal file
43
frigate/api/defs/response/review_response.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from datetime import datetime
|
||||
from typing import Dict
|
||||
|
||||
from pydantic import BaseModel, Json
|
||||
|
||||
from frigate.review.types import SeverityEnum
|
||||
|
||||
|
||||
class ReviewSegmentResponse(BaseModel):
|
||||
id: str
|
||||
camera: str
|
||||
start_time: datetime
|
||||
end_time: datetime
|
||||
has_been_reviewed: bool
|
||||
severity: SeverityEnum
|
||||
thumb_path: str
|
||||
data: Json
|
||||
|
||||
|
||||
class Last24HoursReview(BaseModel):
|
||||
reviewed_alert: int
|
||||
reviewed_detection: int
|
||||
total_alert: int
|
||||
total_detection: int
|
||||
|
||||
|
||||
class DayReview(BaseModel):
|
||||
day: datetime
|
||||
reviewed_alert: int
|
||||
reviewed_detection: int
|
||||
total_alert: int
|
||||
total_detection: int
|
||||
|
||||
|
||||
class ReviewSummaryResponse(BaseModel):
|
||||
last24Hours: Last24HoursReview
|
||||
root: Dict[str, DayReview]
|
||||
|
||||
|
||||
class ReviewActivityMotionResponse(BaseModel):
|
||||
start_time: int
|
||||
motion: float
|
||||
camera: str
|
||||
@@ -1,28 +0,0 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ReviewQueryParams(BaseModel):
|
||||
cameras: Optional[str] = "all"
|
||||
labels: Optional[str] = "all"
|
||||
zones: Optional[str] = "all"
|
||||
reviewed: Optional[int] = 0
|
||||
limit: Optional[int] = None
|
||||
severity: Optional[str] = None
|
||||
before: Optional[float] = None
|
||||
after: Optional[float] = None
|
||||
|
||||
|
||||
class ReviewSummaryQueryParams(BaseModel):
|
||||
cameras: Optional[str] = "all"
|
||||
labels: Optional[str] = "all"
|
||||
zones: Optional[str] = "all"
|
||||
timezone: Optional[str] = "utc"
|
||||
|
||||
|
||||
class ReviewActivityMotionQueryParams(BaseModel):
|
||||
cameras: Optional[str] = "all"
|
||||
before: Optional[float] = None
|
||||
after: Optional[float] = None
|
||||
scale: Optional[int] = 30
|
||||
@@ -14,29 +14,36 @@ from fastapi.responses import JSONResponse
|
||||
from peewee import JOIN, DoesNotExist, fn, operator
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.api.defs.events_body import (
|
||||
EventsCreateBody,
|
||||
EventsDescriptionBody,
|
||||
EventsEndBody,
|
||||
EventsSubLabelBody,
|
||||
SubmitPlusBody,
|
||||
)
|
||||
from frigate.api.defs.events_query_parameters import (
|
||||
from frigate.api.defs.query.events_query_parameters import (
|
||||
DEFAULT_TIME_RANGE,
|
||||
EventsQueryParams,
|
||||
EventsSearchQueryParams,
|
||||
EventsSummaryQueryParams,
|
||||
)
|
||||
from frigate.api.defs.regenerate_query_parameters import (
|
||||
from frigate.api.defs.query.regenerate_query_parameters import (
|
||||
RegenerateQueryParameters,
|
||||
)
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.const import (
|
||||
CLIPS_DIR,
|
||||
from frigate.api.defs.request.events_body import (
|
||||
EventsCreateBody,
|
||||
EventsDeleteBody,
|
||||
EventsDescriptionBody,
|
||||
EventsEndBody,
|
||||
EventsSubLabelBody,
|
||||
SubmitPlusBody,
|
||||
)
|
||||
from frigate.api.defs.response.event_response import (
|
||||
EventCreateResponse,
|
||||
EventMultiDeleteResponse,
|
||||
EventResponse,
|
||||
EventUploadPlusResponse,
|
||||
)
|
||||
from frigate.api.defs.response.generic_response import GenericResponse
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.const import CLIPS_DIR
|
||||
from frigate.embeddings import EmbeddingsContext
|
||||
from frigate.events.external import ExternalEventProcessor
|
||||
from frigate.models import Event, ReviewSegment, Timeline
|
||||
from frigate.object_processing import TrackedObject
|
||||
from frigate.object_processing import TrackedObject, TrackedObjectProcessor
|
||||
from frigate.util.builtin import get_tz_modifiers
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -44,7 +51,7 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(tags=[Tags.events])
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
@router.get("/events", response_model=list[EventResponse])
|
||||
def events(params: EventsQueryParams = Depends()):
|
||||
camera = params.camera
|
||||
cameras = params.cameras
|
||||
@@ -88,6 +95,7 @@ def events(params: EventsQueryParams = Depends()):
|
||||
is_submitted = params.is_submitted
|
||||
min_length = params.min_length
|
||||
max_length = params.max_length
|
||||
event_id = params.event_id
|
||||
|
||||
sort = params.sort
|
||||
|
||||
@@ -230,6 +238,9 @@ def events(params: EventsQueryParams = Depends()):
|
||||
elif is_submitted > 0:
|
||||
clauses.append((Event.plus_id != ""))
|
||||
|
||||
if event_id is not None:
|
||||
clauses.append((Event.id == event_id))
|
||||
|
||||
if len(clauses) == 0:
|
||||
clauses.append((True))
|
||||
|
||||
@@ -242,6 +253,8 @@ def events(params: EventsQueryParams = Depends()):
|
||||
order_by = Event.start_time.asc()
|
||||
elif sort == "date_desc":
|
||||
order_by = Event.start_time.desc()
|
||||
else:
|
||||
order_by = Event.start_time.desc()
|
||||
else:
|
||||
order_by = Event.start_time.desc()
|
||||
|
||||
@@ -257,7 +270,7 @@ def events(params: EventsQueryParams = Depends()):
|
||||
return JSONResponse(content=list(events))
|
||||
|
||||
|
||||
@router.get("/events/explore")
|
||||
@router.get("/events/explore", response_model=list[EventResponse])
|
||||
def events_explore(limit: int = 10):
|
||||
# get distinct labels for all events
|
||||
distinct_labels = Event.select(Event.label).distinct().order_by(Event.label)
|
||||
@@ -302,7 +315,8 @@ def events_explore(limit: int = 10):
|
||||
"data": {
|
||||
k: v
|
||||
for k, v in event.data.items()
|
||||
if k in ["type", "score", "top_score", "description"]
|
||||
if k
|
||||
in ["type", "score", "top_score", "description", "sub_label_score"]
|
||||
},
|
||||
"event_count": label_counts[event.label],
|
||||
}
|
||||
@@ -318,7 +332,7 @@ def events_explore(limit: int = 10):
|
||||
return JSONResponse(content=processed_events)
|
||||
|
||||
|
||||
@router.get("/event_ids")
|
||||
@router.get("/event_ids", response_model=list[EventResponse])
|
||||
def event_ids(ids: str):
|
||||
ids = ids.split(",")
|
||||
|
||||
@@ -356,6 +370,7 @@ def events_search(request: Request, params: EventsSearchQueryParams = Depends())
|
||||
time_range = params.time_range
|
||||
has_clip = params.has_clip
|
||||
has_snapshot = params.has_snapshot
|
||||
is_submitted = params.is_submitted
|
||||
|
||||
# for similarity search
|
||||
event_id = params.event_id
|
||||
@@ -394,6 +409,7 @@ def events_search(request: Request, params: EventsSearchQueryParams = Depends())
|
||||
Event.end_time,
|
||||
Event.has_clip,
|
||||
Event.has_snapshot,
|
||||
Event.top_score,
|
||||
Event.data,
|
||||
Event.plus_id,
|
||||
ReviewSegment.thumb_path,
|
||||
@@ -436,6 +452,12 @@ def events_search(request: Request, params: EventsSearchQueryParams = Depends())
|
||||
if has_snapshot is not None:
|
||||
event_filters.append((Event.has_snapshot == has_snapshot))
|
||||
|
||||
if is_submitted is not None:
|
||||
if is_submitted == 0:
|
||||
event_filters.append((Event.plus_id.is_null()))
|
||||
elif is_submitted > 0:
|
||||
event_filters.append((Event.plus_id != ""))
|
||||
|
||||
if min_score is not None and max_score is not None:
|
||||
event_filters.append((Event.data["score"].between(min_score, max_score)))
|
||||
else:
|
||||
@@ -568,19 +590,17 @@ def events_search(request: Request, params: EventsSearchQueryParams = Depends())
|
||||
|
||||
processed_events.append(processed_event)
|
||||
|
||||
# Sort by search distance if search_results are available, otherwise by start_time as default
|
||||
if search_results:
|
||||
if (sort is None or sort == "relevance") and search_results:
|
||||
processed_events.sort(key=lambda x: x.get("search_distance", float("inf")))
|
||||
elif min_score is not None and max_score is not None and sort == "score_asc":
|
||||
processed_events.sort(key=lambda x: x["score"])
|
||||
elif min_score is not None and max_score is not None and sort == "score_desc":
|
||||
processed_events.sort(key=lambda x: x["score"], reverse=True)
|
||||
elif sort == "date_asc":
|
||||
processed_events.sort(key=lambda x: x["start_time"])
|
||||
else:
|
||||
if sort == "score_asc":
|
||||
processed_events.sort(key=lambda x: x["score"])
|
||||
elif sort == "score_desc":
|
||||
processed_events.sort(key=lambda x: x["score"], reverse=True)
|
||||
elif sort == "date_asc":
|
||||
processed_events.sort(key=lambda x: x["start_time"])
|
||||
else:
|
||||
# "date_desc" default
|
||||
processed_events.sort(key=lambda x: x["start_time"], reverse=True)
|
||||
# "date_desc" default
|
||||
processed_events.sort(key=lambda x: x["start_time"], reverse=True)
|
||||
|
||||
# Limit the number of events returned
|
||||
processed_events = processed_events[:limit]
|
||||
@@ -633,7 +653,7 @@ def events_summary(params: EventsSummaryQueryParams = Depends()):
|
||||
return JSONResponse(content=[e for e in groups.dicts()])
|
||||
|
||||
|
||||
@router.get("/events/{event_id}")
|
||||
@router.get("/events/{event_id}", response_model=EventResponse)
|
||||
def event(event_id: str):
|
||||
try:
|
||||
return model_to_dict(Event.get(Event.id == event_id))
|
||||
@@ -641,7 +661,7 @@ def event(event_id: str):
|
||||
return JSONResponse(content="Event not found", status_code=404)
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/retain")
|
||||
@router.post("/events/{event_id}/retain", response_model=GenericResponse)
|
||||
def set_retain(event_id: str):
|
||||
try:
|
||||
event = Event.get(Event.id == event_id)
|
||||
@@ -660,7 +680,7 @@ def set_retain(event_id: str):
|
||||
)
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/plus")
|
||||
@router.post("/events/{event_id}/plus", response_model=EventUploadPlusResponse)
|
||||
def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = None):
|
||||
if not request.app.frigate_config.plus_api.is_active():
|
||||
message = "PLUS_API_KEY environment variable is not set"
|
||||
@@ -772,7 +792,7 @@ def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = None):
|
||||
)
|
||||
|
||||
|
||||
@router.put("/events/{event_id}/false_positive")
|
||||
@router.put("/events/{event_id}/false_positive", response_model=EventUploadPlusResponse)
|
||||
def false_positive(request: Request, event_id: str):
|
||||
if not request.app.frigate_config.plus_api.is_active():
|
||||
message = "PLUS_API_KEY environment variable is not set"
|
||||
@@ -861,7 +881,7 @@ def false_positive(request: Request, event_id: str):
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/events/{event_id}/retain")
|
||||
@router.delete("/events/{event_id}/retain", response_model=GenericResponse)
|
||||
def delete_retain(event_id: str):
|
||||
try:
|
||||
event = Event.get(Event.id == event_id)
|
||||
@@ -880,7 +900,7 @@ def delete_retain(event_id: str):
|
||||
)
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/sub_label")
|
||||
@router.post("/events/{event_id}/sub_label", response_model=GenericResponse)
|
||||
def set_sub_label(
|
||||
request: Request,
|
||||
event_id: str,
|
||||
@@ -932,7 +952,7 @@ def set_sub_label(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/events/{event_id}/description")
|
||||
@router.post("/events/{event_id}/description", response_model=GenericResponse)
|
||||
def set_description(
|
||||
request: Request,
|
||||
event_id: str,
|
||||
@@ -979,7 +999,7 @@ def set_description(
|
||||
)
|
||||
|
||||
|
||||
@router.put("/events/{event_id}/description/regenerate")
|
||||
@router.put("/events/{event_id}/description/regenerate", response_model=GenericResponse)
|
||||
def regenerate_description(
|
||||
request: Request, event_id: str, params: RegenerateQueryParameters = Depends()
|
||||
):
|
||||
@@ -991,9 +1011,11 @@ def regenerate_description(
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
camera_config = request.app.frigate_config.cameras[event.camera]
|
||||
|
||||
if (
|
||||
request.app.frigate_config.semantic_search.enabled
|
||||
and request.app.frigate_config.genai.enabled
|
||||
and camera_config.genai.enabled
|
||||
):
|
||||
request.app.event_metadata_updater.publish((event.id, params.source))
|
||||
|
||||
@@ -1014,47 +1036,74 @@ def regenerate_description(
|
||||
content=(
|
||||
{
|
||||
"success": False,
|
||||
"message": "Semantic search and generative AI are not enabled",
|
||||
"message": "Semantic Search and Generative AI must be enabled to regenerate a description",
|
||||
}
|
||||
),
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/events/{event_id}")
|
||||
def delete_event(request: Request, event_id: str):
|
||||
def delete_single_event(event_id: str, request: Request) -> dict:
|
||||
try:
|
||||
event = Event.get(Event.id == event_id)
|
||||
except DoesNotExist:
|
||||
return JSONResponse(
|
||||
content=({"success": False, "message": "Event " + event_id + " not found"}),
|
||||
status_code=404,
|
||||
)
|
||||
return {"success": False, "message": f"Event {event_id} not found"}
|
||||
|
||||
media_name = f"{event.camera}-{event.id}"
|
||||
if event.has_snapshot:
|
||||
media = Path(f"{os.path.join(CLIPS_DIR, media_name)}.jpg")
|
||||
media.unlink(missing_ok=True)
|
||||
media = Path(f"{os.path.join(CLIPS_DIR, media_name)}-clean.png")
|
||||
media.unlink(missing_ok=True)
|
||||
if event.has_clip:
|
||||
media = Path(f"{os.path.join(CLIPS_DIR, media_name)}.mp4")
|
||||
media.unlink(missing_ok=True)
|
||||
snapshot_paths = [
|
||||
Path(f"{os.path.join(CLIPS_DIR, media_name)}.jpg"),
|
||||
Path(f"{os.path.join(CLIPS_DIR, media_name)}-clean.png"),
|
||||
]
|
||||
for media in snapshot_paths:
|
||||
media.unlink(missing_ok=True)
|
||||
|
||||
event.delete_instance()
|
||||
Timeline.delete().where(Timeline.source_id == event_id).execute()
|
||||
|
||||
# If semantic search is enabled, update the index
|
||||
if request.app.frigate_config.semantic_search.enabled:
|
||||
context: EmbeddingsContext = request.app.embeddings
|
||||
context.db.delete_embeddings_thumbnail(event_ids=[event_id])
|
||||
context.db.delete_embeddings_description(event_ids=[event_id])
|
||||
return JSONResponse(
|
||||
content=({"success": True, "message": "Event " + event_id + " deleted"}),
|
||||
status_code=200,
|
||||
)
|
||||
|
||||
return {"success": True, "message": f"Event {event_id} deleted"}
|
||||
|
||||
|
||||
@router.post("/events/{camera_name}/{label}/create")
|
||||
@router.delete("/events/{event_id}", response_model=GenericResponse)
|
||||
def delete_event(request: Request, event_id: str):
|
||||
result = delete_single_event(event_id, request)
|
||||
status_code = 200 if result["success"] else 404
|
||||
return JSONResponse(content=result, status_code=status_code)
|
||||
|
||||
|
||||
@router.delete("/events/", response_model=EventMultiDeleteResponse)
|
||||
def delete_events(request: Request, body: EventsDeleteBody):
|
||||
if not body.event_ids:
|
||||
return JSONResponse(
|
||||
content=({"success": False, "message": "No event IDs provided."}),
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
deleted_events = []
|
||||
not_found_events = []
|
||||
|
||||
for event_id in body.event_ids:
|
||||
result = delete_single_event(event_id, request)
|
||||
if result["success"]:
|
||||
deleted_events.append(event_id)
|
||||
else:
|
||||
not_found_events.append(event_id)
|
||||
|
||||
response = {
|
||||
"success": True,
|
||||
"deleted_events": deleted_events,
|
||||
"not_found_events": not_found_events,
|
||||
}
|
||||
return JSONResponse(content=response, status_code=200)
|
||||
|
||||
|
||||
@router.post("/events/{camera_name}/{label}/create", response_model=EventCreateResponse)
|
||||
def create_event(
|
||||
request: Request,
|
||||
camera_name: str,
|
||||
@@ -1076,9 +1125,11 @@ def create_event(
|
||||
)
|
||||
|
||||
try:
|
||||
frame = request.app.detected_frames_processor.get_current_frame(camera_name)
|
||||
frame_processor: TrackedObjectProcessor = request.app.detected_frames_processor
|
||||
external_processor: ExternalEventProcessor = request.app.external_processor
|
||||
|
||||
event_id = request.app.external_processor.create_manual_event(
|
||||
frame = frame_processor.get_current_frame(camera_name)
|
||||
event_id = external_processor.create_manual_event(
|
||||
camera_name,
|
||||
label,
|
||||
body.source_type,
|
||||
@@ -1108,7 +1159,7 @@ def create_event(
|
||||
)
|
||||
|
||||
|
||||
@router.put("/events/{event_id}/end")
|
||||
@router.put("/events/{event_id}/end", response_model=GenericResponse)
|
||||
def end_event(request: Request, event_id: str, body: EventsEndBody):
|
||||
try:
|
||||
end_time = body.end_time or datetime.datetime.now().timestamp()
|
||||
|
||||
@@ -4,17 +4,23 @@ import logging
|
||||
import random
|
||||
import string
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import psutil
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from peewee import DoesNotExist
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.api.defs.request.export_recordings_body import ExportRecordingsBody
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.const import EXPORT_DIR
|
||||
from frigate.models import Export, Recordings
|
||||
from frigate.record.export import PlaybackFactorEnum, RecordingExporter
|
||||
from frigate.models import Export, Previews, Recordings
|
||||
from frigate.record.export import (
|
||||
PlaybackFactorEnum,
|
||||
PlaybackSourceEnum,
|
||||
RecordingExporter,
|
||||
)
|
||||
from frigate.util.builtin import is_current_hour
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -33,7 +39,7 @@ def export_recording(
|
||||
camera_name: str,
|
||||
start_time: float,
|
||||
end_time: float,
|
||||
body: dict = None,
|
||||
body: ExportRecordingsBody,
|
||||
):
|
||||
if not camera_name or not request.app.frigate_config.cameras.get(camera_name):
|
||||
return JSONResponse(
|
||||
@@ -43,36 +49,52 @@ def export_recording(
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
json: dict[str, any] = body or {}
|
||||
playback_factor = json.get("playback", "realtime")
|
||||
friendly_name: Optional[str] = json.get("name")
|
||||
playback_factor = body.playback
|
||||
playback_source = body.source
|
||||
friendly_name = body.name
|
||||
existing_image = body.image_path
|
||||
|
||||
if len(friendly_name or "") > 256:
|
||||
return JSONResponse(
|
||||
content=({"success": False, "message": "File name is too long."}),
|
||||
status_code=401,
|
||||
if playback_source == "recordings":
|
||||
recordings_count = (
|
||||
Recordings.select()
|
||||
.where(
|
||||
Recordings.start_time.between(start_time, end_time)
|
||||
| Recordings.end_time.between(start_time, end_time)
|
||||
| (
|
||||
(start_time > Recordings.start_time)
|
||||
& (end_time < Recordings.end_time)
|
||||
)
|
||||
)
|
||||
.where(Recordings.camera == camera_name)
|
||||
.count()
|
||||
)
|
||||
|
||||
existing_image = json.get("image_path")
|
||||
|
||||
recordings_count = (
|
||||
Recordings.select()
|
||||
.where(
|
||||
Recordings.start_time.between(start_time, end_time)
|
||||
| Recordings.end_time.between(start_time, end_time)
|
||||
| ((start_time > Recordings.start_time) & (end_time < Recordings.end_time))
|
||||
if recordings_count <= 0:
|
||||
return JSONResponse(
|
||||
content=(
|
||||
{"success": False, "message": "No recordings found for time range"}
|
||||
),
|
||||
status_code=400,
|
||||
)
|
||||
else:
|
||||
previews_count = (
|
||||
Previews.select()
|
||||
.where(
|
||||
Previews.start_time.between(start_time, end_time)
|
||||
| Previews.end_time.between(start_time, end_time)
|
||||
| ((start_time > Previews.start_time) & (end_time < Previews.end_time))
|
||||
)
|
||||
.where(Previews.camera == camera_name)
|
||||
.count()
|
||||
)
|
||||
.where(Recordings.camera == camera_name)
|
||||
.count()
|
||||
)
|
||||
|
||||
if recordings_count <= 0:
|
||||
return JSONResponse(
|
||||
content=(
|
||||
{"success": False, "message": "No recordings found for time range"}
|
||||
),
|
||||
status_code=400,
|
||||
)
|
||||
if not is_current_hour(start_time) and previews_count <= 0:
|
||||
return JSONResponse(
|
||||
content=(
|
||||
{"success": False, "message": "No previews found for time range"}
|
||||
),
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
export_id = f"{camera_name}_{''.join(random.choices(string.ascii_lowercase + string.digits, k=6))}"
|
||||
exporter = RecordingExporter(
|
||||
@@ -88,6 +110,11 @@ def export_recording(
|
||||
if playback_factor in PlaybackFactorEnum.__members__.values()
|
||||
else PlaybackFactorEnum.realtime
|
||||
),
|
||||
(
|
||||
PlaybackSourceEnum[playback_source]
|
||||
if playback_source in PlaybackSourceEnum.__members__.values()
|
||||
else PlaybackSourceEnum.recordings
|
||||
),
|
||||
)
|
||||
exporter.start()
|
||||
return JSONResponse(
|
||||
@@ -181,3 +208,14 @@ def export_delete(event_id: str):
|
||||
),
|
||||
status_code=200,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exports/{export_id}")
|
||||
def get_export(export_id: str):
|
||||
try:
|
||||
return JSONResponse(content=model_to_dict(Export.get(Export.id == export_id)))
|
||||
except DoesNotExist:
|
||||
return JSONResponse(
|
||||
content={"success": False, "message": "Export not found"},
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
@@ -82,8 +82,16 @@ def create_fastapi_app(
|
||||
database.close()
|
||||
return response
|
||||
|
||||
@app.on_event("startup")
|
||||
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)
|
||||
|
||||
@@ -20,7 +20,7 @@ from pathvalidate import sanitize_filename
|
||||
from peewee import DoesNotExist, fn
|
||||
from tzlocal import get_localzone_name
|
||||
|
||||
from frigate.api.defs.media_query_parameters import (
|
||||
from frigate.api.defs.query.media_query_parameters import (
|
||||
Extension,
|
||||
MediaEventsSnapshotQueryParams,
|
||||
MediaLatestFrameQueryParams,
|
||||
@@ -36,6 +36,7 @@ from frigate.const import (
|
||||
RECORD_DIR,
|
||||
)
|
||||
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
|
||||
from frigate.object_processing import TrackedObjectProcessor
|
||||
from frigate.util.builtin import get_tz_modifiers
|
||||
from frigate.util.image import get_image_from_recording
|
||||
|
||||
@@ -79,7 +80,11 @@ def mjpeg_feed(
|
||||
|
||||
|
||||
def imagestream(
|
||||
detected_frames_processor, camera_name: str, fps: int, height: int, draw_options
|
||||
detected_frames_processor: TrackedObjectProcessor,
|
||||
camera_name: str,
|
||||
fps: int,
|
||||
height: int,
|
||||
draw_options: dict[str, any],
|
||||
):
|
||||
while True:
|
||||
# max out at specified FPS
|
||||
@@ -118,6 +123,7 @@ def latest_frame(
|
||||
extension: Extension,
|
||||
params: MediaLatestFrameQueryParams = Depends(),
|
||||
):
|
||||
frame_processor: TrackedObjectProcessor = request.app.detected_frames_processor
|
||||
draw_options = {
|
||||
"bounding_boxes": params.bbox,
|
||||
"timestamp": params.timestamp,
|
||||
@@ -129,17 +135,14 @@ def latest_frame(
|
||||
quality = params.quality
|
||||
|
||||
if camera_name in request.app.frigate_config.cameras:
|
||||
frame = request.app.detected_frames_processor.get_current_frame(
|
||||
camera_name, draw_options
|
||||
)
|
||||
frame = frame_processor.get_current_frame(camera_name, draw_options)
|
||||
retry_interval = float(
|
||||
request.app.frigate_config.cameras.get(camera_name).ffmpeg.retry_interval
|
||||
or 10
|
||||
)
|
||||
|
||||
if frame is None or datetime.now().timestamp() > (
|
||||
request.app.detected_frames_processor.get_current_frame_time(camera_name)
|
||||
+ retry_interval
|
||||
frame_processor.get_current_frame_time(camera_name) + retry_interval
|
||||
):
|
||||
if request.app.camera_error_image is None:
|
||||
error_image = glob.glob("/opt/frigate/frigate/images/camera-error.jpg")
|
||||
@@ -180,7 +183,7 @@ def latest_frame(
|
||||
)
|
||||
elif camera_name == "birdseye" and request.app.frigate_config.birdseye.restream:
|
||||
frame = cv2.cvtColor(
|
||||
request.app.detected_frames_processor.get_current_frame(camera_name),
|
||||
frame_processor.get_current_frame(camera_name),
|
||||
cv2.COLOR_YUV2BGR_I420,
|
||||
)
|
||||
|
||||
@@ -460,8 +463,8 @@ def recording_clip(
|
||||
text=False,
|
||||
) as ffmpeg:
|
||||
while True:
|
||||
data = ffmpeg.stdout.read(1024)
|
||||
if data is not None:
|
||||
data = ffmpeg.stdout.read(8192)
|
||||
if data is not None and len(data) > 0:
|
||||
yield data
|
||||
else:
|
||||
if ffmpeg.returncode and ffmpeg.returncode != 0:
|
||||
@@ -813,15 +816,15 @@ def grid_snapshot(
|
||||
):
|
||||
if camera_name in request.app.frigate_config.cameras:
|
||||
detect = request.app.frigate_config.cameras[camera_name].detect
|
||||
frame = request.app.detected_frames_processor.get_current_frame(camera_name, {})
|
||||
frame_processor: TrackedObjectProcessor = request.app.detected_frames_processor
|
||||
frame = frame_processor.get_current_frame(camera_name, {})
|
||||
retry_interval = float(
|
||||
request.app.frigate_config.cameras.get(camera_name).ffmpeg.retry_interval
|
||||
or 10
|
||||
)
|
||||
|
||||
if frame is None or datetime.now().timestamp() > (
|
||||
request.app.detected_frames_processor.get_current_frame_time(camera_name)
|
||||
+ retry_interval
|
||||
frame_processor.get_current_frame_time(camera_name) + retry_interval
|
||||
):
|
||||
return JSONResponse(
|
||||
content={"success": False, "message": "Unable to get valid frame"},
|
||||
@@ -917,7 +920,7 @@ def grid_snapshot(
|
||||
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
|
||||
|
||||
return Response(
|
||||
jpg.tobytes,
|
||||
jpg.tobytes(),
|
||||
media_type="image/jpeg",
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
@@ -1453,7 +1456,6 @@ def preview_thumbnail(file_name: str):
|
||||
|
||||
return Response(
|
||||
jpg_bytes,
|
||||
# FIXME: Shouldn't it be either jpg or webp depending on the endpoint?
|
||||
media_type="image/webp",
|
||||
headers={
|
||||
"Content-Type": "image/webp",
|
||||
@@ -1482,7 +1484,7 @@ def label_thumbnail(request: Request, camera_name: str, label: str):
|
||||
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
|
||||
|
||||
return Response(
|
||||
jpg.tobytes,
|
||||
jpg.tobytes(),
|
||||
media_type="image/jpeg",
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
@@ -1535,6 +1537,6 @@ def label_snapshot(request: Request, camera_name: str, label: str):
|
||||
_, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
|
||||
|
||||
return Response(
|
||||
jpg.tobytes,
|
||||
jpg.tobytes(),
|
||||
media_type="image/jpeg",
|
||||
)
|
||||
|
||||
@@ -12,13 +12,21 @@ from fastapi.responses import JSONResponse
|
||||
from peewee import Case, DoesNotExist, fn, operator
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.api.defs.review_query_parameters import (
|
||||
from frigate.api.defs.query.review_query_parameters import (
|
||||
ReviewActivityMotionQueryParams,
|
||||
ReviewQueryParams,
|
||||
ReviewSummaryQueryParams,
|
||||
)
|
||||
from frigate.api.defs.request.review_body import ReviewModifyMultipleBody
|
||||
from frigate.api.defs.response.generic_response import GenericResponse
|
||||
from frigate.api.defs.response.review_response import (
|
||||
ReviewActivityMotionResponse,
|
||||
ReviewSegmentResponse,
|
||||
ReviewSummaryResponse,
|
||||
)
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.models import Recordings, ReviewSegment
|
||||
from frigate.review.types import SeverityEnum
|
||||
from frigate.util.builtin import get_tz_modifiers
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -26,7 +34,7 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(tags=[Tags.review])
|
||||
|
||||
|
||||
@router.get("/review")
|
||||
@router.get("/review", response_model=list[ReviewSegmentResponse])
|
||||
def review(params: ReviewQueryParams = Depends()):
|
||||
cameras = params.cameras
|
||||
labels = params.labels
|
||||
@@ -102,7 +110,7 @@ def review(params: ReviewQueryParams = Depends()):
|
||||
return JSONResponse(content=[r for r in review])
|
||||
|
||||
|
||||
@router.get("/review/summary")
|
||||
@router.get("/review/summary", response_model=ReviewSummaryResponse)
|
||||
def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
hour_modifier, minute_modifier, seconds_offset = get_tz_modifiers(params.timezone)
|
||||
day_ago = (datetime.datetime.now() - datetime.timedelta(hours=24)).timestamp()
|
||||
@@ -154,7 +162,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "alert"),
|
||||
(ReviewSegment.severity == SeverityEnum.alert),
|
||||
ReviewSegment.has_been_reviewed,
|
||||
)
|
||||
],
|
||||
@@ -166,7 +174,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "detection"),
|
||||
(ReviewSegment.severity == SeverityEnum.detection),
|
||||
ReviewSegment.has_been_reviewed,
|
||||
)
|
||||
],
|
||||
@@ -178,19 +186,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "significant_motion"),
|
||||
ReviewSegment.has_been_reviewed,
|
||||
)
|
||||
],
|
||||
0,
|
||||
)
|
||||
).alias("reviewed_motion"),
|
||||
fn.SUM(
|
||||
Case(
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "alert"),
|
||||
(ReviewSegment.severity == SeverityEnum.alert),
|
||||
1,
|
||||
)
|
||||
],
|
||||
@@ -202,25 +198,13 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "detection"),
|
||||
(ReviewSegment.severity == SeverityEnum.detection),
|
||||
1,
|
||||
)
|
||||
],
|
||||
0,
|
||||
)
|
||||
).alias("total_detection"),
|
||||
fn.SUM(
|
||||
Case(
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "significant_motion"),
|
||||
1,
|
||||
)
|
||||
],
|
||||
0,
|
||||
)
|
||||
).alias("total_motion"),
|
||||
)
|
||||
.where(reduce(operator.and_, clauses))
|
||||
.dicts()
|
||||
@@ -247,6 +231,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
label_clause = reduce(operator.or_, label_clauses)
|
||||
clauses.append((label_clause))
|
||||
|
||||
day_in_seconds = 60 * 60 * 24
|
||||
last_month = (
|
||||
ReviewSegment.select(
|
||||
fn.strftime(
|
||||
@@ -263,7 +248,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "alert"),
|
||||
(ReviewSegment.severity == SeverityEnum.alert),
|
||||
ReviewSegment.has_been_reviewed,
|
||||
)
|
||||
],
|
||||
@@ -275,7 +260,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "detection"),
|
||||
(ReviewSegment.severity == SeverityEnum.detection),
|
||||
ReviewSegment.has_been_reviewed,
|
||||
)
|
||||
],
|
||||
@@ -287,19 +272,7 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "significant_motion"),
|
||||
ReviewSegment.has_been_reviewed,
|
||||
)
|
||||
],
|
||||
0,
|
||||
)
|
||||
).alias("reviewed_motion"),
|
||||
fn.SUM(
|
||||
Case(
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "alert"),
|
||||
(ReviewSegment.severity == SeverityEnum.alert),
|
||||
1,
|
||||
)
|
||||
],
|
||||
@@ -311,29 +284,17 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "detection"),
|
||||
(ReviewSegment.severity == SeverityEnum.detection),
|
||||
1,
|
||||
)
|
||||
],
|
||||
0,
|
||||
)
|
||||
).alias("total_detection"),
|
||||
fn.SUM(
|
||||
Case(
|
||||
None,
|
||||
[
|
||||
(
|
||||
(ReviewSegment.severity == "significant_motion"),
|
||||
1,
|
||||
)
|
||||
],
|
||||
0,
|
||||
)
|
||||
).alias("total_motion"),
|
||||
)
|
||||
.where(reduce(operator.and_, clauses))
|
||||
.group_by(
|
||||
(ReviewSegment.start_time + seconds_offset).cast("int") / (3600 * 24),
|
||||
(ReviewSegment.start_time + seconds_offset).cast("int") / day_in_seconds,
|
||||
)
|
||||
.order_by(ReviewSegment.start_time.desc())
|
||||
)
|
||||
@@ -348,19 +309,10 @@ def review_summary(params: ReviewSummaryQueryParams = Depends()):
|
||||
return JSONResponse(content=data)
|
||||
|
||||
|
||||
@router.post("/reviews/viewed")
|
||||
def set_multiple_reviewed(body: dict = None):
|
||||
json: dict[str, any] = body or {}
|
||||
list_of_ids = json.get("ids", "")
|
||||
|
||||
if not list_of_ids or len(list_of_ids) == 0:
|
||||
return JSONResponse(
|
||||
context=({"success": False, "message": "Not a valid list of ids"}),
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
@router.post("/reviews/viewed", response_model=GenericResponse)
|
||||
def set_multiple_reviewed(body: ReviewModifyMultipleBody):
|
||||
ReviewSegment.update(has_been_reviewed=True).where(
|
||||
ReviewSegment.id << list_of_ids
|
||||
ReviewSegment.id << body.ids
|
||||
).execute()
|
||||
|
||||
return JSONResponse(
|
||||
@@ -369,17 +321,9 @@ def set_multiple_reviewed(body: dict = None):
|
||||
)
|
||||
|
||||
|
||||
@router.post("/reviews/delete")
|
||||
def delete_reviews(body: dict = None):
|
||||
json: dict[str, any] = body or {}
|
||||
list_of_ids = json.get("ids", "")
|
||||
|
||||
if not list_of_ids or len(list_of_ids) == 0:
|
||||
return JSONResponse(
|
||||
content=({"success": False, "message": "Not a valid list of ids"}),
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
@router.post("/reviews/delete", response_model=GenericResponse)
|
||||
def delete_reviews(body: ReviewModifyMultipleBody):
|
||||
list_of_ids = body.ids
|
||||
reviews = (
|
||||
ReviewSegment.select(
|
||||
ReviewSegment.camera,
|
||||
@@ -420,11 +364,13 @@ def delete_reviews(body: dict = None):
|
||||
ReviewSegment.delete().where(ReviewSegment.id << list_of_ids).execute()
|
||||
|
||||
return JSONResponse(
|
||||
content=({"success": True, "message": "Delete reviews"}), status_code=200
|
||||
content=({"success": True, "message": "Deleted review items."}), status_code=200
|
||||
)
|
||||
|
||||
|
||||
@router.get("/review/activity/motion")
|
||||
@router.get(
|
||||
"/review/activity/motion", response_model=list[ReviewActivityMotionResponse]
|
||||
)
|
||||
def motion_activity(params: ReviewActivityMotionQueryParams = Depends()):
|
||||
"""Get motion and audio activity."""
|
||||
cameras = params.cameras
|
||||
@@ -498,98 +444,44 @@ def motion_activity(params: ReviewActivityMotionQueryParams = Depends()):
|
||||
return JSONResponse(content=normalized)
|
||||
|
||||
|
||||
@router.get("/review/activity/audio")
|
||||
def audio_activity(params: ReviewActivityMotionQueryParams = Depends()):
|
||||
"""Get motion and audio activity."""
|
||||
cameras = params.cameras
|
||||
before = params.before or datetime.datetime.now().timestamp()
|
||||
after = (
|
||||
params.after
|
||||
or (datetime.datetime.now() - datetime.timedelta(hours=1)).timestamp()
|
||||
)
|
||||
# get scale in seconds
|
||||
scale = params.scale
|
||||
|
||||
clauses = [(Recordings.start_time > after) & (Recordings.end_time < before)]
|
||||
|
||||
if cameras != "all":
|
||||
camera_list = cameras.split(",")
|
||||
clauses.append((Recordings.camera << camera_list))
|
||||
|
||||
all_recordings: list[Recordings] = (
|
||||
Recordings.select(
|
||||
Recordings.start_time,
|
||||
Recordings.duration,
|
||||
Recordings.objects,
|
||||
Recordings.dBFS,
|
||||
)
|
||||
.where(reduce(operator.and_, clauses))
|
||||
.order_by(Recordings.start_time.asc())
|
||||
.iterator()
|
||||
)
|
||||
|
||||
# format is: { timestamp: segment_start_ts, motion: [0-100], audio: [0 - -100] }
|
||||
# periods where active objects / audio was detected will cause audio to be scaled down
|
||||
data: list[dict[str, float]] = []
|
||||
|
||||
for rec in all_recordings:
|
||||
data.append(
|
||||
{
|
||||
"start_time": rec.start_time,
|
||||
"audio": rec.dBFS if rec.objects == 0 else 0,
|
||||
}
|
||||
)
|
||||
|
||||
# resample data using pandas to get activity on scaled basis
|
||||
df = pd.DataFrame(data, columns=["start_time", "audio"])
|
||||
df = df.astype(dtype={"audio": "float16"})
|
||||
|
||||
# set date as datetime index
|
||||
df["start_time"] = pd.to_datetime(df["start_time"], unit="s")
|
||||
df.set_index(["start_time"], inplace=True)
|
||||
|
||||
# normalize data
|
||||
df = df.resample(f"{scale}S").mean().fillna(0.0)
|
||||
df["audio"] = (
|
||||
(df["audio"] - df["audio"].max())
|
||||
/ (df["audio"].min() - df["audio"].max())
|
||||
* -100
|
||||
)
|
||||
|
||||
# change types for output
|
||||
df.index = df.index.astype(int) // (10**9)
|
||||
normalized = df.reset_index().to_dict("records")
|
||||
return JSONResponse(content=normalized)
|
||||
|
||||
|
||||
@router.get("/review/event/{event_id}")
|
||||
@router.get("/review/event/{event_id}", response_model=ReviewSegmentResponse)
|
||||
def get_review_from_event(event_id: str):
|
||||
try:
|
||||
return model_to_dict(
|
||||
ReviewSegment.get(
|
||||
ReviewSegment.data["detections"].cast("text") % f'*"{event_id}"*'
|
||||
return JSONResponse(
|
||||
model_to_dict(
|
||||
ReviewSegment.get(
|
||||
ReviewSegment.data["detections"].cast("text") % f'*"{event_id}"*'
|
||||
)
|
||||
)
|
||||
)
|
||||
except DoesNotExist:
|
||||
return "Review item not found", 404
|
||||
return JSONResponse(
|
||||
content={"success": False, "message": "Review item not found"},
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/review/{event_id}")
|
||||
def get_review(event_id: str):
|
||||
@router.get("/review/{review_id}", response_model=ReviewSegmentResponse)
|
||||
def get_review(review_id: str):
|
||||
try:
|
||||
return model_to_dict(ReviewSegment.get(ReviewSegment.id == event_id))
|
||||
return JSONResponse(
|
||||
content=model_to_dict(ReviewSegment.get(ReviewSegment.id == review_id))
|
||||
)
|
||||
except DoesNotExist:
|
||||
return "Review item not found", 404
|
||||
return JSONResponse(
|
||||
content={"success": False, "message": "Review item not found"},
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/review/{event_id}/viewed")
|
||||
def set_not_reviewed(event_id: str):
|
||||
@router.delete("/review/{review_id}/viewed", response_model=GenericResponse)
|
||||
def set_not_reviewed(review_id: str):
|
||||
try:
|
||||
review: ReviewSegment = ReviewSegment.get(ReviewSegment.id == event_id)
|
||||
review: ReviewSegment = ReviewSegment.get(ReviewSegment.id == review_id)
|
||||
except DoesNotExist:
|
||||
return JSONResponse(
|
||||
content=(
|
||||
{"success": False, "message": "Review " + event_id + " not found"}
|
||||
{"success": False, "message": "Review " + review_id + " not found"}
|
||||
),
|
||||
status_code=404,
|
||||
)
|
||||
@@ -598,6 +490,8 @@ def set_not_reviewed(event_id: str):
|
||||
review.save()
|
||||
|
||||
return JSONResponse(
|
||||
content=({"success": True, "message": "Reviewed " + event_id + " not viewed"}),
|
||||
content=(
|
||||
{"success": True, "message": "Set Review " + review_id + " as not viewed"}
|
||||
),
|
||||
status_code=200,
|
||||
)
|
||||
|
||||
@@ -36,6 +36,7 @@ from frigate.const import (
|
||||
EXPORT_DIR,
|
||||
MODEL_CACHE_DIR,
|
||||
RECORD_DIR,
|
||||
SHM_FRAMES_VAR,
|
||||
)
|
||||
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
|
||||
from frigate.embeddings import EmbeddingsContext, manage_embeddings
|
||||
@@ -68,6 +69,7 @@ from frigate.stats.util import stats_init
|
||||
from frigate.storage import StorageMaintainer
|
||||
from frigate.timeline import TimelineProcessor
|
||||
from frigate.util.builtin import empty_and_close_queue
|
||||
from frigate.util.image import SharedMemoryFrameManager, UntrackedSharedMemory
|
||||
from frigate.util.object import get_camera_regions_grid
|
||||
from frigate.version import VERSION
|
||||
from frigate.video import capture_camera, track_camera
|
||||
@@ -90,6 +92,7 @@ class FrigateApp:
|
||||
self.processes: dict[str, int] = {}
|
||||
self.embeddings: Optional[EmbeddingsContext] = None
|
||||
self.region_grids: dict[str, list[list[dict[str, int]]]] = {}
|
||||
self.frame_manager = SharedMemoryFrameManager()
|
||||
self.config = config
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
@@ -325,20 +328,20 @@ class FrigateApp:
|
||||
for det in self.config.detectors.values()
|
||||
]
|
||||
)
|
||||
shm_in = mp.shared_memory.SharedMemory(
|
||||
shm_in = UntrackedSharedMemory(
|
||||
name=name,
|
||||
create=True,
|
||||
size=largest_frame,
|
||||
)
|
||||
except FileExistsError:
|
||||
shm_in = mp.shared_memory.SharedMemory(name=name)
|
||||
shm_in = UntrackedSharedMemory(name=name)
|
||||
|
||||
try:
|
||||
shm_out = mp.shared_memory.SharedMemory(
|
||||
shm_out = UntrackedSharedMemory(
|
||||
name=f"out-{name}", create=True, size=20 * 6 * 4
|
||||
)
|
||||
except FileExistsError:
|
||||
shm_out = mp.shared_memory.SharedMemory(name=f"out-{name}")
|
||||
shm_out = UntrackedSharedMemory(name=f"out-{name}")
|
||||
|
||||
self.detection_shms.append(shm_in)
|
||||
self.detection_shms.append(shm_out)
|
||||
@@ -431,6 +434,11 @@ class FrigateApp:
|
||||
logger.info(f"Capture process not started for disabled camera {name}")
|
||||
continue
|
||||
|
||||
# pre-create shms
|
||||
for i in range(shm_frame_count):
|
||||
frame_size = config.frame_shape_yuv[0] * config.frame_shape_yuv[1]
|
||||
self.frame_manager.create(f"{config.name}_{i}", frame_size)
|
||||
|
||||
capture_process = util.Process(
|
||||
target=capture_camera,
|
||||
name=f"camera_capture:{name}",
|
||||
@@ -513,15 +521,21 @@ class FrigateApp:
|
||||
1,
|
||||
)
|
||||
|
||||
shm_frame_count = min(50, int(available_shm / (cam_total_frame_size)))
|
||||
if cam_total_frame_size == 0.0:
|
||||
return 0
|
||||
|
||||
shm_frame_count = min(
|
||||
int(os.environ.get(SHM_FRAMES_VAR, "50")),
|
||||
int(available_shm / (cam_total_frame_size)),
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Calculated total camera size {available_shm} / {cam_total_frame_size} :: {shm_frame_count} frames for each camera in SHM"
|
||||
)
|
||||
|
||||
if shm_frame_count < 10:
|
||||
if shm_frame_count < 20:
|
||||
logger.warning(
|
||||
f"The current SHM size of {total_shm}MB is too small, recommend increasing it to at least {round(min_req_shm + cam_total_frame_size * 10)}MB."
|
||||
f"The current SHM size of {total_shm}MB is too small, recommend increasing it to at least {round(min_req_shm + cam_total_frame_size * 20)}MB."
|
||||
)
|
||||
|
||||
return shm_frame_count
|
||||
@@ -707,6 +721,7 @@ class FrigateApp:
|
||||
self.event_metadata_updater.stop()
|
||||
self.inter_zmq_proxy.stop()
|
||||
|
||||
self.frame_manager.cleanup()
|
||||
while len(self.detection_shms) > 0:
|
||||
shm = self.detection_shms.pop()
|
||||
shm.close()
|
||||
|
||||
@@ -22,7 +22,7 @@ from frigate.const import (
|
||||
)
|
||||
from frigate.models import Event, Previews, Recordings, ReviewSegment
|
||||
from frigate.ptz.onvif import OnvifCommandEnum, OnvifController
|
||||
from frigate.types import ModelStatusTypesEnum
|
||||
from frigate.types import ModelStatusTypesEnum, TrackedObjectUpdateTypesEnum
|
||||
from frigate.util.object import get_camera_regions_grid
|
||||
from frigate.util.services import restart_frigate
|
||||
|
||||
@@ -137,8 +137,14 @@ class Dispatcher:
|
||||
event.data["description"] = payload["description"]
|
||||
event.save()
|
||||
self.publish(
|
||||
"event_update",
|
||||
json.dumps({"id": event.id, "description": event.data["description"]}),
|
||||
"tracked_object_update",
|
||||
json.dumps(
|
||||
{
|
||||
"type": TrackedObjectUpdateTypesEnum.description,
|
||||
"id": event.id,
|
||||
"description": event.data["description"],
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
def handle_update_model_state():
|
||||
|
||||
@@ -14,7 +14,7 @@ class EventUpdatePublisher(Publisher):
|
||||
super().__init__("update")
|
||||
|
||||
def publish(
|
||||
self, payload: tuple[EventTypeEnum, EventStateEnum, str, dict[str, any]]
|
||||
self, payload: tuple[EventTypeEnum, EventStateEnum, str, str, dict[str, any]]
|
||||
) -> None:
|
||||
super().publish(payload)
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ class MqttClient(Communicator): # type: ignore[misc]
|
||||
def __init__(self, config: FrigateConfig) -> None:
|
||||
self.config = config
|
||||
self.mqtt_config = config.mqtt
|
||||
self.connected: bool = False
|
||||
self.connected = False
|
||||
|
||||
def subscribe(self, receiver: Callable) -> None:
|
||||
"""Wrapper for allowing dispatcher to subscribe."""
|
||||
@@ -27,7 +27,7 @@ class MqttClient(Communicator): # type: ignore[misc]
|
||||
def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
|
||||
"""Wrapper for publishing when client is in valid state."""
|
||||
if not self.connected:
|
||||
logger.error(f"Unable to publish to {topic}: client is not connected")
|
||||
logger.debug(f"Unable to publish to {topic}: client is not connected")
|
||||
return
|
||||
|
||||
self.client.publish(
|
||||
@@ -133,7 +133,7 @@ class MqttClient(Communicator): # type: ignore[misc]
|
||||
"""Mqtt connection callback."""
|
||||
threading.current_thread().name = "mqtt"
|
||||
if reason_code != 0:
|
||||
if reason_code == "Server Unavailable":
|
||||
if reason_code == "Server unavailable":
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: MQTT Server unavailable"
|
||||
)
|
||||
@@ -173,6 +173,7 @@ class MqttClient(Communicator): # type: ignore[misc]
|
||||
client_id=self.mqtt_config.client_id,
|
||||
)
|
||||
self.client.on_connect = self._on_connect
|
||||
self.client.on_disconnect = self._on_disconnect
|
||||
self.client.will_set(
|
||||
self.mqtt_config.topic_prefix + "/available",
|
||||
payload="offline",
|
||||
@@ -197,14 +198,6 @@ class MqttClient(Communicator): # type: ignore[misc]
|
||||
|
||||
for name in self.config.cameras.keys():
|
||||
for callback in callback_types:
|
||||
# We need to pre-clear existing set topics because in previous
|
||||
# versions the webUI retained on the /set topic but this is
|
||||
# no longer the case.
|
||||
self.client.publish(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/{callback}/set",
|
||||
None,
|
||||
retain=True,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/{callback}/set",
|
||||
self.on_mqtt_command,
|
||||
|
||||
@@ -13,7 +13,7 @@ class AuthConfig(FrigateBaseModel):
|
||||
default=False, title="Reset the admin password on startup"
|
||||
)
|
||||
cookie_name: str = Field(
|
||||
default="frigate_token", title="Name for jwt token cookie", pattern=r"^[a-z]_*$"
|
||||
default="frigate_token", title="Name for jwt token cookie", pattern=r"^[a-z_]+$"
|
||||
)
|
||||
cookie_secure: bool = Field(default=False, title="Set secure flag on cookie")
|
||||
session_length: int = Field(
|
||||
|
||||
@@ -94,3 +94,10 @@ class RecordConfig(FrigateBaseModel):
|
||||
enabled_in_config: Optional[bool] = Field(
|
||||
default=None, title="Keep track of original state of recording."
|
||||
)
|
||||
|
||||
@property
|
||||
def event_pre_capture(self) -> int:
|
||||
return max(
|
||||
self.alerts.pre_capture,
|
||||
self.detections.pre_capture,
|
||||
)
|
||||
|
||||
@@ -29,6 +29,7 @@ from frigate.util.builtin import (
|
||||
)
|
||||
from frigate.util.config import (
|
||||
StreamInfoRetriever,
|
||||
find_config_file,
|
||||
get_relative_coordinates,
|
||||
migrate_frigate_config,
|
||||
)
|
||||
@@ -67,7 +68,6 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
yaml = YAML()
|
||||
|
||||
DEFAULT_CONFIG_FILES = ["/config/config.yaml", "/config/config.yml"]
|
||||
DEFAULT_CONFIG = """
|
||||
mqtt:
|
||||
enabled: False
|
||||
@@ -230,12 +230,16 @@ def verify_recording_segments_setup_with_reasonable_time(
|
||||
try:
|
||||
seg_arg_index = record_args.index("-segment_time")
|
||||
except ValueError:
|
||||
raise ValueError(f"Camera {camera_config.name} has no segment_time in \
|
||||
recording output args, segment args are required for record.")
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has no segment_time in \
|
||||
recording output args, segment args are required for record."
|
||||
)
|
||||
|
||||
if int(record_args[seg_arg_index + 1]) > 60:
|
||||
raise ValueError(f"Camera {camera_config.name} has invalid segment_time output arg, \
|
||||
segment_time must be 60 or less.")
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has invalid segment_time output arg, \
|
||||
segment_time must be 60 or less."
|
||||
)
|
||||
|
||||
|
||||
def verify_zone_objects_are_tracked(camera_config: CameraConfig) -> None:
|
||||
@@ -634,27 +638,20 @@ class FrigateConfig(FrigateBaseModel):
|
||||
|
||||
@classmethod
|
||||
def load(cls, **kwargs):
|
||||
config_path = os.environ.get("CONFIG_FILE")
|
||||
|
||||
# No explicit configuration file, try to find one in the default paths.
|
||||
if config_path is None:
|
||||
for path in DEFAULT_CONFIG_FILES:
|
||||
if os.path.isfile(path):
|
||||
config_path = path
|
||||
break
|
||||
config_path = find_config_file()
|
||||
|
||||
# No configuration file found, create one.
|
||||
new_config = False
|
||||
if config_path is None:
|
||||
if not os.path.isfile(config_path):
|
||||
logger.info("No config file found, saving default config")
|
||||
config_path = DEFAULT_CONFIG_FILES[-1]
|
||||
config_path = config_path
|
||||
new_config = True
|
||||
else:
|
||||
# Check if the config file needs to be migrated.
|
||||
migrate_frigate_config(config_path)
|
||||
|
||||
# Finally, load the resulting configuration file.
|
||||
with open(config_path, "a+") as f:
|
||||
with open(config_path, "a+" if new_config else "r") as f:
|
||||
# Only write the default config if the opened file is non-empty. This can happen as
|
||||
# a race condition. It's extremely unlikely, but eh. Might as well check it.
|
||||
if new_config and f.tell() == 0:
|
||||
|
||||
@@ -23,7 +23,7 @@ EnvString = Annotated[str, AfterValidator(validate_env_string)]
|
||||
|
||||
def validate_env_vars(v: dict[str, str], info: ValidationInfo) -> dict[str, str]:
|
||||
if isinstance(info.context, dict) and info.context.get("install", False):
|
||||
for k, v in v:
|
||||
for k, v in v.items():
|
||||
os.environ[k] = v
|
||||
|
||||
return v
|
||||
|
||||
@@ -13,6 +13,8 @@ FRIGATE_LOCALHOST = "http://127.0.0.1:5000"
|
||||
PLUS_ENV_VAR = "PLUS_API_KEY"
|
||||
PLUS_API_HOST = "https://api.frigate.video"
|
||||
|
||||
SHM_FRAMES_VAR = "SHM_MAX_FRAMES"
|
||||
|
||||
# Attribute & Object constants
|
||||
|
||||
DEFAULT_ATTRIBUTE_LABEL_MAP = {
|
||||
|
||||
@@ -27,6 +27,11 @@ class InputTensorEnum(str, Enum):
|
||||
nhwc = "nhwc"
|
||||
|
||||
|
||||
class InputDTypeEnum(str, Enum):
|
||||
float = "float"
|
||||
int = "int"
|
||||
|
||||
|
||||
class ModelTypeEnum(str, Enum):
|
||||
ssd = "ssd"
|
||||
yolox = "yolox"
|
||||
@@ -53,6 +58,9 @@ class ModelConfig(BaseModel):
|
||||
input_pixel_format: PixelFormatEnum = Field(
|
||||
default=PixelFormatEnum.rgb, title="Model Input Pixel Color Format"
|
||||
)
|
||||
input_dtype: InputDTypeEnum = Field(
|
||||
default=InputDTypeEnum.int, title="Model Input D Type"
|
||||
)
|
||||
model_type: ModelTypeEnum = Field(
|
||||
default=ModelTypeEnum.ssd, title="Object Detection Model Type"
|
||||
)
|
||||
|
||||
@@ -32,6 +32,7 @@ class DeepStack(DetectionApi):
|
||||
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 @@ class DeepStack(DetectionApi):
|
||||
data = {"api_key": self.api_key}
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
response = self.session.post(
|
||||
self.api_url,
|
||||
data=data,
|
||||
files={"image": image_bytes},
|
||||
|
||||
@@ -54,7 +54,7 @@ class ONNXDetector(DetectionApi):
|
||||
|
||||
logger.info(f"ONNX: {path} loaded")
|
||||
|
||||
def detect_raw(self, tensor_input):
|
||||
def detect_raw(self, tensor_input: np.ndarray):
|
||||
model_input_name = self.model.get_inputs()[0].name
|
||||
tensor_output = self.model.run(None, {model_input_name: tensor_input})
|
||||
|
||||
|
||||
@@ -136,17 +136,17 @@ class Rknn(DetectionApi):
|
||||
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):
|
||||
|
||||
@@ -98,9 +98,7 @@ class ROCmDetector(DetectionApi):
|
||||
else:
|
||||
logger.info(f"AMD/ROCm: loading model from {path}")
|
||||
|
||||
if path.endswith(".onnx"):
|
||||
self.model = migraphx.parse_onnx(path)
|
||||
elif (
|
||||
if (
|
||||
path.endswith(".tf")
|
||||
or path.endswith(".tf2")
|
||||
or path.endswith(".tflite")
|
||||
@@ -108,7 +106,7 @@ class ROCmDetector(DetectionApi):
|
||||
# untested
|
||||
self.model = migraphx.parse_tf(path)
|
||||
else:
|
||||
raise Exception(f"AMD/ROCm: unknown model format {path}")
|
||||
self.model = migraphx.parse_onnx(path)
|
||||
|
||||
logger.info("AMD/ROCm: compiling the model")
|
||||
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
"""SQLite-vec embeddings database."""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
from numpy import ndarray
|
||||
from PIL import Image
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.comms.inter_process import InterProcessRequestor
|
||||
@@ -22,7 +20,7 @@ from frigate.models import Event
|
||||
from frigate.types import ModelStatusTypesEnum
|
||||
from frigate.util.builtin import serialize
|
||||
|
||||
from .functions.onnx import GenericONNXEmbedding
|
||||
from .functions.onnx import GenericONNXEmbedding, ModelTypeEnum
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -97,7 +95,7 @@ class Embeddings:
|
||||
"text_model_fp16.onnx": "https://huggingface.co/jinaai/jina-clip-v1/resolve/main/onnx/text_model_fp16.onnx",
|
||||
},
|
||||
model_size=config.model_size,
|
||||
model_type="text",
|
||||
model_type=ModelTypeEnum.text,
|
||||
requestor=self.requestor,
|
||||
device="CPU",
|
||||
)
|
||||
@@ -118,83 +116,102 @@ class Embeddings:
|
||||
model_file=model_file,
|
||||
download_urls=download_urls,
|
||||
model_size=config.model_size,
|
||||
model_type="vision",
|
||||
model_type=ModelTypeEnum.vision,
|
||||
requestor=self.requestor,
|
||||
device="GPU" if config.model_size == "large" else "CPU",
|
||||
)
|
||||
|
||||
def upsert_thumbnail(self, event_id: str, thumbnail: bytes) -> ndarray:
|
||||
# Convert thumbnail bytes to PIL Image
|
||||
image = Image.open(io.BytesIO(thumbnail)).convert("RGB")
|
||||
embedding = self.vision_embedding([image])[0]
|
||||
def embed_thumbnail(
|
||||
self, event_id: str, thumbnail: bytes, upsert: bool = True
|
||||
) -> ndarray:
|
||||
"""Embed thumbnail and optionally insert into DB.
|
||||
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_thumbnails(id, thumbnail_embedding)
|
||||
VALUES(?, ?)
|
||||
""",
|
||||
(event_id, serialize(embedding)),
|
||||
)
|
||||
@param: event_id in Events DB
|
||||
@param: thumbnail bytes in jpg format
|
||||
@param: upsert If embedding should be upserted into vec DB
|
||||
"""
|
||||
# Convert thumbnail bytes to PIL Image
|
||||
embedding = self.vision_embedding([thumbnail])[0]
|
||||
|
||||
if upsert:
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_thumbnails(id, thumbnail_embedding)
|
||||
VALUES(?, ?)
|
||||
""",
|
||||
(event_id, serialize(embedding)),
|
||||
)
|
||||
|
||||
return embedding
|
||||
|
||||
def batch_upsert_thumbnail(self, event_thumbs: dict[str, bytes]) -> list[ndarray]:
|
||||
images = [
|
||||
Image.open(io.BytesIO(thumb)).convert("RGB")
|
||||
for thumb in event_thumbs.values()
|
||||
]
|
||||
def batch_embed_thumbnail(
|
||||
self, event_thumbs: dict[str, bytes], upsert: bool = True
|
||||
) -> list[ndarray]:
|
||||
"""Embed thumbnails and optionally insert into DB.
|
||||
|
||||
@param: event_thumbs Map of Event IDs in DB to thumbnail bytes in jpg format
|
||||
@param: upsert If embedding should be upserted into vec DB
|
||||
"""
|
||||
ids = list(event_thumbs.keys())
|
||||
embeddings = self.vision_embedding(images)
|
||||
embeddings = self.vision_embedding(list(event_thumbs.values()))
|
||||
|
||||
items = []
|
||||
if upsert:
|
||||
items = []
|
||||
|
||||
for i in range(len(ids)):
|
||||
items.append(ids[i])
|
||||
items.append(serialize(embeddings[i]))
|
||||
for i in range(len(ids)):
|
||||
items.append(ids[i])
|
||||
items.append(serialize(embeddings[i]))
|
||||
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_thumbnails(id, thumbnail_embedding)
|
||||
VALUES {}
|
||||
""".format(", ".join(["(?, ?)"] * len(ids))),
|
||||
items,
|
||||
)
|
||||
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_thumbnails(id, thumbnail_embedding)
|
||||
VALUES {}
|
||||
""".format(", ".join(["(?, ?)"] * len(ids))),
|
||||
items,
|
||||
)
|
||||
return embeddings
|
||||
|
||||
def upsert_description(self, event_id: str, description: str) -> ndarray:
|
||||
def embed_description(
|
||||
self, event_id: str, description: str, upsert: bool = True
|
||||
) -> ndarray:
|
||||
embedding = self.text_embedding([description])[0]
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_descriptions(id, description_embedding)
|
||||
VALUES(?, ?)
|
||||
""",
|
||||
(event_id, serialize(embedding)),
|
||||
)
|
||||
|
||||
if upsert:
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_descriptions(id, description_embedding)
|
||||
VALUES(?, ?)
|
||||
""",
|
||||
(event_id, serialize(embedding)),
|
||||
)
|
||||
|
||||
return embedding
|
||||
|
||||
def batch_upsert_description(self, event_descriptions: dict[str, str]) -> ndarray:
|
||||
def batch_embed_description(
|
||||
self, event_descriptions: dict[str, str], upsert: bool = True
|
||||
) -> ndarray:
|
||||
# upsert embeddings one by one to avoid token limit
|
||||
embeddings = []
|
||||
|
||||
for desc in event_descriptions.values():
|
||||
embeddings.append(self.text_embedding([desc])[0])
|
||||
|
||||
ids = list(event_descriptions.keys())
|
||||
if upsert:
|
||||
ids = list(event_descriptions.keys())
|
||||
items = []
|
||||
|
||||
items = []
|
||||
for i in range(len(ids)):
|
||||
items.append(ids[i])
|
||||
items.append(serialize(embeddings[i]))
|
||||
|
||||
for i in range(len(ids)):
|
||||
items.append(ids[i])
|
||||
items.append(serialize(embeddings[i]))
|
||||
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_descriptions(id, description_embedding)
|
||||
VALUES {}
|
||||
""".format(", ".join(["(?, ?)"] * len(ids))),
|
||||
items,
|
||||
)
|
||||
self.db.execute_sql(
|
||||
"""
|
||||
INSERT OR REPLACE INTO vec_descriptions(id, description_embedding)
|
||||
VALUES {}
|
||||
""".format(", ".join(["(?, ?)"] * len(ids))),
|
||||
items,
|
||||
)
|
||||
|
||||
return embeddings
|
||||
|
||||
@@ -261,10 +278,10 @@ class Embeddings:
|
||||
totals["processed_objects"] += 1
|
||||
|
||||
# run batch embedding
|
||||
self.batch_upsert_thumbnail(batch_thumbs)
|
||||
self.batch_embed_thumbnail(batch_thumbs)
|
||||
|
||||
if batch_descs:
|
||||
self.batch_upsert_description(batch_descs)
|
||||
self.batch_embed_description(batch_descs)
|
||||
|
||||
# report progress every batch so we don't spam the logs
|
||||
progress = (totals["processed_objects"] / total_events) * 100
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
import warnings
|
||||
from enum import Enum
|
||||
from io import BytesIO
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
@@ -31,6 +32,12 @@ disable_progress_bar()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ModelTypeEnum(str, Enum):
|
||||
face = "face"
|
||||
vision = "vision"
|
||||
text = "text"
|
||||
|
||||
|
||||
class GenericONNXEmbedding:
|
||||
"""Generic embedding function for ONNX models (text and vision)."""
|
||||
|
||||
@@ -88,7 +95,10 @@ class GenericONNXEmbedding:
|
||||
file_name = os.path.basename(path)
|
||||
if file_name in self.download_urls:
|
||||
ModelDownloader.download_from_url(self.download_urls[file_name], path)
|
||||
elif file_name == self.tokenizer_file and self.model_type == "text":
|
||||
elif (
|
||||
file_name == self.tokenizer_file
|
||||
and self.model_type == ModelTypeEnum.text
|
||||
):
|
||||
if not os.path.exists(path + "/" + self.model_name):
|
||||
logger.info(f"Downloading {self.model_name} tokenizer")
|
||||
tokenizer = AutoTokenizer.from_pretrained(
|
||||
@@ -119,7 +129,7 @@ class GenericONNXEmbedding:
|
||||
if self.runner is None:
|
||||
if self.downloader:
|
||||
self.downloader.wait_for_download()
|
||||
if self.model_type == "text":
|
||||
if self.model_type == ModelTypeEnum.text:
|
||||
self.tokenizer = self._load_tokenizer()
|
||||
else:
|
||||
self.feature_extractor = self._load_feature_extractor()
|
||||
@@ -143,11 +153,35 @@ class GenericONNXEmbedding:
|
||||
f"{MODEL_CACHE_DIR}/{self.model_name}",
|
||||
)
|
||||
|
||||
def _preprocess_inputs(self, raw_inputs: any) -> any:
|
||||
if self.model_type == ModelTypeEnum.text:
|
||||
max_length = max(len(self.tokenizer.encode(text)) for text in raw_inputs)
|
||||
return [
|
||||
self.tokenizer(
|
||||
text,
|
||||
padding="max_length",
|
||||
truncation=True,
|
||||
max_length=max_length,
|
||||
return_tensors="np",
|
||||
)
|
||||
for text in raw_inputs
|
||||
]
|
||||
elif self.model_type == ModelTypeEnum.vision:
|
||||
processed_images = [self._process_image(img) for img in raw_inputs]
|
||||
return [
|
||||
self.feature_extractor(images=image, return_tensors="np")
|
||||
for image in processed_images
|
||||
]
|
||||
else:
|
||||
raise ValueError(f"Unable to preprocess inputs for {self.model_type}")
|
||||
|
||||
def _process_image(self, image):
|
||||
if isinstance(image, str):
|
||||
if image.startswith("http"):
|
||||
response = requests.get(image)
|
||||
image = Image.open(BytesIO(response.content)).convert("RGB")
|
||||
elif isinstance(image, bytes):
|
||||
image = Image.open(BytesIO(image)).convert("RGB")
|
||||
|
||||
return image
|
||||
|
||||
@@ -163,25 +197,7 @@ class GenericONNXEmbedding:
|
||||
)
|
||||
return []
|
||||
|
||||
if self.model_type == "text":
|
||||
max_length = max(len(self.tokenizer.encode(text)) for text in inputs)
|
||||
processed_inputs = [
|
||||
self.tokenizer(
|
||||
text,
|
||||
padding="max_length",
|
||||
truncation=True,
|
||||
max_length=max_length,
|
||||
return_tensors="np",
|
||||
)
|
||||
for text in inputs
|
||||
]
|
||||
else:
|
||||
processed_images = [self._process_image(img) for img in inputs]
|
||||
processed_inputs = [
|
||||
self.feature_extractor(images=image, return_tensors="np")
|
||||
for image in processed_images
|
||||
]
|
||||
|
||||
processed_inputs = self._preprocess_inputs(inputs)
|
||||
input_names = self.runner.get_input_names()
|
||||
onnx_inputs = {name: [] for name in input_names}
|
||||
input: dict[str, any]
|
||||
|
||||
@@ -24,6 +24,7 @@ from frigate.const import CLIPS_DIR, UPDATE_EVENT_DESCRIPTION
|
||||
from frigate.events.types import EventTypeEnum
|
||||
from frigate.genai import get_genai_client
|
||||
from frigate.models import Event
|
||||
from frigate.types import TrackedObjectUpdateTypesEnum
|
||||
from frigate.util.builtin import serialize
|
||||
from frigate.util.image import SharedMemoryFrameManager, calculate_region
|
||||
|
||||
@@ -62,7 +63,7 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
self.requestor = InterProcessRequestor()
|
||||
self.stop_event = stop_event
|
||||
self.tracked_events = {}
|
||||
self.genai_client = get_genai_client(config.genai)
|
||||
self.genai_client = get_genai_client(config)
|
||||
|
||||
def run(self) -> None:
|
||||
"""Maintain a SQLite-vec database for semantic search."""
|
||||
@@ -86,7 +87,7 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
try:
|
||||
if topic == EmbeddingsRequestEnum.embed_description.value:
|
||||
return serialize(
|
||||
self.embeddings.upsert_description(
|
||||
self.embeddings.embed_description(
|
||||
data["id"], data["description"]
|
||||
),
|
||||
pack=False,
|
||||
@@ -94,7 +95,7 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
elif topic == EmbeddingsRequestEnum.embed_thumbnail.value:
|
||||
thumbnail = base64.b64decode(data["thumbnail"])
|
||||
return serialize(
|
||||
self.embeddings.upsert_thumbnail(data["id"], thumbnail),
|
||||
self.embeddings.embed_thumbnail(data["id"], thumbnail),
|
||||
pack=False,
|
||||
)
|
||||
elif topic == EmbeddingsRequestEnum.generate_search.value:
|
||||
@@ -113,7 +114,7 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
if update is None:
|
||||
return
|
||||
|
||||
source_type, _, camera, data = update
|
||||
source_type, _, camera, frame_name, data = update
|
||||
|
||||
if not camera or source_type != EventTypeEnum.tracked_object:
|
||||
return
|
||||
@@ -133,8 +134,9 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
|
||||
# Create our own thumbnail based on the bounding box and the frame time
|
||||
try:
|
||||
frame_id = f"{camera}{data['frame_time']}"
|
||||
yuv_frame = self.frame_manager.get(frame_id, camera_config.frame_shape_yuv)
|
||||
yuv_frame = self.frame_manager.get(
|
||||
frame_name, camera_config.frame_shape_yuv
|
||||
)
|
||||
|
||||
if yuv_frame is not None:
|
||||
data["thumbnail"] = self._create_thumbnail(yuv_frame, data["box"])
|
||||
@@ -146,7 +148,7 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
|
||||
self.tracked_events[data["id"]].append(data)
|
||||
|
||||
self.frame_manager.close(frame_id)
|
||||
self.frame_manager.close(frame_name)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
@@ -270,7 +272,7 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
|
||||
def _embed_thumbnail(self, event_id: str, thumbnail: bytes) -> None:
|
||||
"""Embed the thumbnail for an event."""
|
||||
self.embeddings.upsert_thumbnail(event_id, thumbnail)
|
||||
self.embeddings.embed_thumbnail(event_id, thumbnail)
|
||||
|
||||
def _embed_description(self, event: Event, thumbnails: list[bytes]) -> None:
|
||||
"""Embed the description for an event."""
|
||||
@@ -287,11 +289,15 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
# fire and forget description update
|
||||
self.requestor.send_data(
|
||||
UPDATE_EVENT_DESCRIPTION,
|
||||
{"id": event.id, "description": description},
|
||||
{
|
||||
"type": TrackedObjectUpdateTypesEnum.description,
|
||||
"id": event.id,
|
||||
"description": description,
|
||||
},
|
||||
)
|
||||
|
||||
# Encode the description
|
||||
self.embeddings.upsert_description(event.id, description)
|
||||
# Embed the description
|
||||
self.embeddings.embed_description(event.id, description)
|
||||
|
||||
logger.debug(
|
||||
"Generated description for %s (%d images): %s",
|
||||
@@ -319,18 +325,25 @@ class EmbeddingMaintainer(threading.Thread):
|
||||
)
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
# 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[
|
||||
|
||||
@@ -64,6 +64,8 @@ def get_ffmpeg_command(ffmpeg: FfmpegConfig) -> list[str]:
|
||||
|
||||
|
||||
class AudioProcessor(util.Process):
|
||||
name = "frigate.audio_manager"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cameras: list[CameraConfig],
|
||||
@@ -214,6 +216,10 @@ class AudioEventMaintainer(threading.Thread):
|
||||
"label": label,
|
||||
"last_detection": datetime.datetime.now().timestamp(),
|
||||
}
|
||||
else:
|
||||
self.logger.warning(
|
||||
f"Failed to create audio event with status code {resp.status_code}"
|
||||
)
|
||||
|
||||
def expire_detections(self) -> None:
|
||||
now = datetime.datetime.now().timestamp()
|
||||
|
||||
@@ -4,7 +4,6 @@ import datetime
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from enum import Enum
|
||||
from multiprocessing.synchronize import Event as MpEvent
|
||||
from pathlib import Path
|
||||
|
||||
@@ -16,9 +15,7 @@ from frigate.models import Event, Timeline
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EventCleanupType(str, Enum):
|
||||
clips = "clips"
|
||||
snapshots = "snapshots"
|
||||
CHUNK_SIZE = 50
|
||||
|
||||
|
||||
class EventCleanup(threading.Thread):
|
||||
@@ -64,19 +61,11 @@ class EventCleanup(threading.Thread):
|
||||
|
||||
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()
|
||||
|
||||
@@ -84,10 +73,7 @@ class EventCleanup(threading.Thread):
|
||||
# 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)
|
||||
@@ -107,6 +93,7 @@ class EventCleanup(threading.Thread):
|
||||
.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}"
|
||||
@@ -125,25 +112,40 @@ class EventCleanup(threading.Thread):
|
||||
logger.warning(f"Unable to delete event images: {e}")
|
||||
|
||||
# update the clips attribute for the db entry
|
||||
update_query = Event.update(update_params).where(
|
||||
query = Event.select(Event.id).where(
|
||||
Event.camera.not_in(self.camera_keys),
|
||||
Event.start_time < expire_after,
|
||||
Event.label == event.label,
|
||||
Event.retain_indefinitely == False,
|
||||
)
|
||||
update_query.execute()
|
||||
|
||||
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 = []
|
||||
|
||||
## 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)
|
||||
@@ -151,10 +153,9 @@ class EventCleanup(threading.Thread):
|
||||
# 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)
|
||||
@@ -181,28 +182,157 @@ class EventCleanup(threading.Thread):
|
||||
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
|
||||
Event.update(update_params).where(Event.id << events_to_update).execute()
|
||||
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 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"
|
||||
)
|
||||
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):
|
||||
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 run(self) -> None:
|
||||
# only expire events every 5 minutes
|
||||
while not self.stop_event.wait(300):
|
||||
events_with_expired_clips = self.expire(EventCleanupType.clips)
|
||||
events_with_expired_clips = self.expire_clips()
|
||||
|
||||
# delete timeline entries for events that have expired recordings
|
||||
# delete up to 100,000 at a time
|
||||
@@ -213,7 +343,7 @@ class EventCleanup(threading.Thread):
|
||||
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 = (
|
||||
@@ -222,10 +352,11 @@ class EventCleanup(threading.Thread):
|
||||
.iterator()
|
||||
)
|
||||
events_to_delete = [e.id for e in events]
|
||||
logger.debug(f"Found {len(events_to_delete)} events that can be expired")
|
||||
if len(events_to_delete) > 0:
|
||||
chunk_size = 50
|
||||
for i in range(0, len(events_to_delete), chunk_size):
|
||||
chunk = events_to_delete[i : i + chunk_size]
|
||||
for i in range(0, len(events_to_delete), CHUNK_SIZE):
|
||||
chunk = events_to_delete[i : i + CHUNK_SIZE]
|
||||
logger.debug(f"Deleting {len(chunk)} events from the database")
|
||||
Event.delete().where(Event.id << chunk).execute()
|
||||
|
||||
if self.config.semantic_search.enabled:
|
||||
|
||||
@@ -10,6 +10,7 @@ from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
import cv2
|
||||
from numpy import ndarray
|
||||
|
||||
from frigate.comms.detections_updater import DetectionPublisher, DetectionTypeEnum
|
||||
from frigate.comms.events_updater import EventUpdatePublisher
|
||||
@@ -45,7 +46,7 @@ class ExternalEventProcessor:
|
||||
duration: Optional[int],
|
||||
include_recording: bool,
|
||||
draw: dict[str, any],
|
||||
snapshot_frame: any,
|
||||
snapshot_frame: Optional[ndarray],
|
||||
) -> str:
|
||||
now = datetime.datetime.now().timestamp()
|
||||
camera_config = self.config.cameras.get(camera)
|
||||
@@ -64,13 +65,14 @@ class ExternalEventProcessor:
|
||||
EventTypeEnum.api,
|
||||
EventStateEnum.start,
|
||||
camera,
|
||||
"",
|
||||
{
|
||||
"id": event_id,
|
||||
"label": label,
|
||||
"sub_label": sub_label,
|
||||
"score": score,
|
||||
"camera": camera,
|
||||
"start_time": now,
|
||||
"start_time": now - camera_config.record.event_pre_capture,
|
||||
"end_time": end,
|
||||
"thumbnail": thumbnail,
|
||||
"has_clip": camera_config.record.enabled and include_recording,
|
||||
@@ -106,6 +108,7 @@ class ExternalEventProcessor:
|
||||
EventTypeEnum.api,
|
||||
EventStateEnum.end,
|
||||
None,
|
||||
"",
|
||||
{"id": event_id, "end_time": end_time},
|
||||
)
|
||||
)
|
||||
@@ -130,8 +133,11 @@ class ExternalEventProcessor:
|
||||
label: str,
|
||||
event_id: str,
|
||||
draw: dict[str, any],
|
||||
img_frame: any,
|
||||
) -> str:
|
||||
img_frame: Optional[ndarray],
|
||||
) -> Optional[str]:
|
||||
if img_frame is None:
|
||||
return None
|
||||
|
||||
# write clean snapshot if enabled
|
||||
if camera_config.snapshots.clean_copy:
|
||||
ret, png = cv2.imencode(".png", img_frame)
|
||||
|
||||
@@ -75,25 +75,30 @@ class EventProcessor(threading.Thread):
|
||||
if update == None:
|
||||
continue
|
||||
|
||||
source_type, event_type, camera, event_data = update
|
||||
source_type, event_type, camera, _, event_data = update
|
||||
|
||||
logger.debug(
|
||||
f"Event received: {source_type} {event_type} {camera} {event_data['id']}"
|
||||
)
|
||||
|
||||
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 @@ class EventProcessor(threading.Thread):
|
||||
"""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]
|
||||
@@ -210,6 +211,7 @@ class EventProcessor(threading.Thread):
|
||||
"top_score": event_data["top_score"],
|
||||
"attributes": attributes,
|
||||
"type": "object",
|
||||
"max_severity": event_data.get("max_severity"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
"""Generative AI module for Frigate."""
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.config import CameraConfig, GenAIConfig, GenAIProviderEnum
|
||||
from frigate.config import CameraConfig, FrigateConfig, GenAIConfig, GenAIProviderEnum
|
||||
from frigate.models import Event
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PROVIDERS = {}
|
||||
|
||||
|
||||
@@ -41,6 +44,7 @@ class GenAIClient:
|
||||
event.label,
|
||||
camera_config.genai.prompt,
|
||||
).format(**model_to_dict(event))
|
||||
logger.debug(f"Sending images to genai provider with prompt: {prompt}")
|
||||
return self._send(prompt, thumbnails)
|
||||
|
||||
def _init_provider(self):
|
||||
@@ -52,13 +56,19 @@ class GenAIClient:
|
||||
return None
|
||||
|
||||
|
||||
def get_genai_client(genai_config: GenAIConfig) -> Optional[GenAIClient]:
|
||||
def get_genai_client(config: FrigateConfig) -> Optional[GenAIClient]:
|
||||
"""Get the GenAI client."""
|
||||
if genai_config.enabled:
|
||||
genai_config = config.genai
|
||||
genai_cameras = [
|
||||
c for c in config.cameras.values() if c.enabled and c.genai.enabled
|
||||
]
|
||||
|
||||
if genai_cameras:
|
||||
load_providers()
|
||||
provider = PROVIDERS.get(genai_config.provider)
|
||||
if provider:
|
||||
return provider(genai_config)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -38,6 +38,11 @@ class OllamaClient(GenAIClient):
|
||||
|
||||
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,
|
||||
|
||||
@@ -93,7 +93,7 @@ class ReviewSegment(Model): # type: ignore[misc]
|
||||
start_time = DateTimeField()
|
||||
end_time = DateTimeField()
|
||||
has_been_reviewed = BooleanField(default=False)
|
||||
severity = CharField(max_length=30) # alert, detection, significant_motion
|
||||
severity = CharField(max_length=30) # alert, detection
|
||||
thumb_path = CharField(unique=True)
|
||||
data = JSONField() # additional data about detection like list of labels, zone, areas of significant motion
|
||||
|
||||
|
||||
@@ -59,3 +59,7 @@ ignore_errors = false
|
||||
[mypy-frigate.watchdog]
|
||||
ignore_errors = false
|
||||
disallow_untyped_calls = false
|
||||
|
||||
|
||||
[mypy-frigate.service_manager.*]
|
||||
ignore_errors = false
|
||||
|
||||
@@ -12,10 +12,14 @@ from setproctitle import setproctitle
|
||||
|
||||
import frigate.util as util
|
||||
from frigate.detectors import create_detector
|
||||
from frigate.detectors.detector_config import BaseDetectorConfig, InputTensorEnum
|
||||
from frigate.detectors.detector_config import (
|
||||
BaseDetectorConfig,
|
||||
InputDTypeEnum,
|
||||
InputTensorEnum,
|
||||
)
|
||||
from frigate.detectors.plugins.rocm import DETECTOR_KEY as ROCM_DETECTOR_KEY
|
||||
from frigate.util.builtin import EventsPerSecond, load_labels
|
||||
from frigate.util.image import SharedMemoryFrameManager
|
||||
from frigate.util.image import SharedMemoryFrameManager, UntrackedSharedMemory
|
||||
from frigate.util.services import listen
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -55,12 +59,15 @@ class LocalObjectDetector(ObjectDetector):
|
||||
self.input_transform = tensor_transform(
|
||||
detector_config.model.input_tensor
|
||||
)
|
||||
|
||||
self.dtype = detector_config.model.input_dtype
|
||||
else:
|
||||
self.input_transform = None
|
||||
self.dtype = InputDTypeEnum.int
|
||||
|
||||
self.detect_api = create_detector(detector_config)
|
||||
|
||||
def detect(self, tensor_input, threshold=0.4):
|
||||
def detect(self, tensor_input: np.ndarray, threshold=0.4):
|
||||
detections = []
|
||||
|
||||
raw_detections = self.detect_raw(tensor_input)
|
||||
@@ -77,9 +84,14 @@ class LocalObjectDetector(ObjectDetector):
|
||||
self.fps.update()
|
||||
return detections
|
||||
|
||||
def detect_raw(self, tensor_input):
|
||||
def detect_raw(self, tensor_input: np.ndarray):
|
||||
if self.input_transform:
|
||||
tensor_input = np.transpose(tensor_input, self.input_transform)
|
||||
|
||||
if self.dtype == InputDTypeEnum.float:
|
||||
tensor_input = tensor_input.astype(np.float32)
|
||||
tensor_input /= 255
|
||||
|
||||
return self.detect_api.detect_raw(tensor_input=tensor_input)
|
||||
|
||||
|
||||
@@ -110,7 +122,7 @@ def run_detector(
|
||||
|
||||
outputs = {}
|
||||
for name in out_events.keys():
|
||||
out_shm = mp.shared_memory.SharedMemory(name=f"out-{name}", create=False)
|
||||
out_shm = UntrackedSharedMemory(name=f"out-{name}", create=False)
|
||||
out_np = np.ndarray((20, 6), dtype=np.float32, buffer=out_shm.buf)
|
||||
outputs[name] = {"shm": out_shm, "np": out_np}
|
||||
|
||||
@@ -200,15 +212,13 @@ class RemoteObjectDetector:
|
||||
self.detection_queue = detection_queue
|
||||
self.event = event
|
||||
self.stop_event = stop_event
|
||||
self.shm = mp.shared_memory.SharedMemory(name=self.name, create=False)
|
||||
self.shm = UntrackedSharedMemory(name=self.name, create=False)
|
||||
self.np_shm = np.ndarray(
|
||||
(1, model_config.height, model_config.width, 3),
|
||||
dtype=np.uint8,
|
||||
buffer=self.shm.buf,
|
||||
)
|
||||
self.out_shm = mp.shared_memory.SharedMemory(
|
||||
name=f"out-{self.name}", create=False
|
||||
)
|
||||
self.out_shm = UntrackedSharedMemory(name=f"out-{self.name}", create=False)
|
||||
self.out_np_shm = np.ndarray((20, 6), dtype=np.float32, buffer=self.out_shm.buf)
|
||||
|
||||
def detect(self, tensor_input, threshold=0.4):
|
||||
|
||||
@@ -6,7 +6,7 @@ import queue
|
||||
import threading
|
||||
from collections import Counter, defaultdict
|
||||
from multiprocessing.synchronize import Event as MpEvent
|
||||
from typing import Callable
|
||||
from typing import Callable, Optional
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -233,17 +233,18 @@ class CameraState:
|
||||
def on(self, event_type: str, callback: Callable[[dict], None]):
|
||||
self.callbacks[event_type].append(callback)
|
||||
|
||||
def update(self, frame_time, current_detections, motion_boxes, regions):
|
||||
# get the new frame
|
||||
frame_id = f"{self.name}{frame_time}"
|
||||
|
||||
def update(
|
||||
self,
|
||||
frame_name: str,
|
||||
frame_time: float,
|
||||
current_detections: dict[str, dict[str, any]],
|
||||
motion_boxes: list[tuple[int, int, int, int]],
|
||||
regions: list[tuple[int, int, int, int]],
|
||||
):
|
||||
current_frame = self.frame_manager.get(
|
||||
frame_id, self.camera_config.frame_shape_yuv
|
||||
frame_name, self.camera_config.frame_shape_yuv
|
||||
)
|
||||
|
||||
if current_frame is None:
|
||||
logger.debug(f"Failed to get frame {frame_id} from SHM")
|
||||
|
||||
tracked_objects = self.tracked_objects.copy()
|
||||
current_ids = set(current_detections.keys())
|
||||
previous_ids = set(tracked_objects.keys())
|
||||
@@ -261,7 +262,7 @@ class CameraState:
|
||||
|
||||
# call event handlers
|
||||
for c in self.callbacks["start"]:
|
||||
c(self.name, new_obj, frame_time)
|
||||
c(self.name, new_obj, frame_name)
|
||||
|
||||
for id in updated_ids:
|
||||
updated_obj = tracked_objects[id]
|
||||
@@ -271,7 +272,7 @@ class CameraState:
|
||||
|
||||
if autotracker_update or significant_update:
|
||||
for c in self.callbacks["autotrack"]:
|
||||
c(self.name, updated_obj, frame_time)
|
||||
c(self.name, updated_obj, frame_name)
|
||||
|
||||
if thumb_update and current_frame is not None:
|
||||
# ensure this frame is stored in the cache
|
||||
@@ -292,7 +293,7 @@ class CameraState:
|
||||
) or significant_update:
|
||||
# call event handlers
|
||||
for c in self.callbacks["update"]:
|
||||
c(self.name, updated_obj, frame_time)
|
||||
c(self.name, updated_obj, frame_name)
|
||||
updated_obj.last_published = frame_time
|
||||
|
||||
for id in removed_ids:
|
||||
@@ -301,7 +302,7 @@ class CameraState:
|
||||
if "end_time" not in removed_obj.obj_data:
|
||||
removed_obj.obj_data["end_time"] = frame_time
|
||||
for c in self.callbacks["end"]:
|
||||
c(self.name, removed_obj, frame_time)
|
||||
c(self.name, removed_obj, frame_name)
|
||||
|
||||
# TODO: can i switch to looking this up and only changing when an event ends?
|
||||
# maintain best objects
|
||||
@@ -344,6 +345,7 @@ class CameraState:
|
||||
# if the object's thumbnail is not from the current frame, skip
|
||||
if (
|
||||
current_frame is None
|
||||
or obj.thumbnail_data is None
|
||||
or obj.false_positive
|
||||
or obj.thumbnail_data["frame_time"] != frame_time
|
||||
):
|
||||
@@ -366,11 +368,11 @@ class CameraState:
|
||||
):
|
||||
self.best_objects[object_type] = obj
|
||||
for c in self.callbacks["snapshot"]:
|
||||
c(self.name, self.best_objects[object_type], frame_time)
|
||||
c(self.name, self.best_objects[object_type], frame_name)
|
||||
else:
|
||||
self.best_objects[object_type] = obj
|
||||
for c in self.callbacks["snapshot"]:
|
||||
c(self.name, self.best_objects[object_type], frame_time)
|
||||
c(self.name, self.best_objects[object_type], frame_name)
|
||||
|
||||
for c in self.callbacks["camera_activity"]:
|
||||
c(self.name, camera_activity)
|
||||
@@ -445,7 +447,7 @@ class CameraState:
|
||||
c(self.name, obj_name, 0)
|
||||
self.active_object_counts[obj_name] = 0
|
||||
for c in self.callbacks["snapshot"]:
|
||||
c(self.name, self.best_objects[obj_name], frame_time)
|
||||
c(self.name, self.best_objects[obj_name], frame_name)
|
||||
|
||||
# cleanup thumbnail frame cache
|
||||
current_thumb_frames = {
|
||||
@@ -476,7 +478,7 @@ class CameraState:
|
||||
if self.previous_frame_id is not None:
|
||||
self.frame_manager.close(self.previous_frame_id)
|
||||
|
||||
self.previous_frame_id = frame_id
|
||||
self.previous_frame_id = frame_name
|
||||
|
||||
|
||||
class TrackedObjectProcessor(threading.Thread):
|
||||
@@ -516,17 +518,18 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
self.zone_data = defaultdict(lambda: defaultdict(dict))
|
||||
self.active_zone_data = defaultdict(lambda: defaultdict(dict))
|
||||
|
||||
def start(camera, obj: TrackedObject, current_frame_time):
|
||||
def start(camera: str, obj: TrackedObject, frame_name: str):
|
||||
self.event_sender.publish(
|
||||
(
|
||||
EventTypeEnum.tracked_object,
|
||||
EventStateEnum.start,
|
||||
camera,
|
||||
frame_name,
|
||||
obj.to_dict(),
|
||||
)
|
||||
)
|
||||
|
||||
def update(camera, obj: TrackedObject, current_frame_time):
|
||||
def update(camera: str, obj: TrackedObject, frame_name: str):
|
||||
obj.has_snapshot = self.should_save_snapshot(camera, obj)
|
||||
obj.has_clip = self.should_retain_recording(camera, obj)
|
||||
after = obj.to_dict()
|
||||
@@ -542,14 +545,15 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
EventTypeEnum.tracked_object,
|
||||
EventStateEnum.update,
|
||||
camera,
|
||||
frame_name,
|
||||
obj.to_dict(include_thumbnail=True),
|
||||
)
|
||||
)
|
||||
|
||||
def autotrack(camera, obj: TrackedObject, current_frame_time):
|
||||
def autotrack(camera: str, obj: TrackedObject, frame_name: str):
|
||||
self.ptz_autotracker_thread.ptz_autotracker.autotrack_object(camera, obj)
|
||||
|
||||
def end(camera, obj: TrackedObject, current_frame_time):
|
||||
def end(camera: str, obj: TrackedObject, frame_name: str):
|
||||
# populate has_snapshot
|
||||
obj.has_snapshot = self.should_save_snapshot(camera, obj)
|
||||
obj.has_clip = self.should_retain_recording(camera, obj)
|
||||
@@ -604,11 +608,12 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
EventTypeEnum.tracked_object,
|
||||
EventStateEnum.end,
|
||||
camera,
|
||||
frame_name,
|
||||
obj.to_dict(include_thumbnail=True),
|
||||
)
|
||||
)
|
||||
|
||||
def snapshot(camera, obj: TrackedObject, current_frame_time):
|
||||
def snapshot(camera, obj: TrackedObject, frame_name: str):
|
||||
mqtt_config: MqttConfig = self.config.cameras[camera].mqtt
|
||||
if mqtt_config.enabled and self.should_mqtt_snapshot(camera, obj):
|
||||
jpg_bytes = obj.get_jpg_bytes(
|
||||
@@ -697,29 +702,7 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
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.alerts.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
|
||||
@@ -778,13 +761,18 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
else:
|
||||
return {}
|
||||
|
||||
def get_current_frame(self, camera, draw_options={}):
|
||||
def get_current_frame(
|
||||
self, camera: str, draw_options: dict[str, any] = {}
|
||||
) -> Optional[np.ndarray]:
|
||||
if camera == "birdseye":
|
||||
return self.frame_manager.get(
|
||||
"birdseye",
|
||||
(self.config.birdseye.height * 3 // 2, self.config.birdseye.width),
|
||||
)
|
||||
|
||||
if camera not in self.camera_states:
|
||||
return None
|
||||
|
||||
return self.camera_states[camera].get_current_frame(draw_options)
|
||||
|
||||
def get_current_frame_time(self, camera) -> int:
|
||||
@@ -796,6 +784,7 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
try:
|
||||
(
|
||||
camera,
|
||||
frame_name,
|
||||
frame_time,
|
||||
current_tracked_objects,
|
||||
motion_boxes,
|
||||
@@ -807,7 +796,7 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
camera_state = self.camera_states[camera]
|
||||
|
||||
camera_state.update(
|
||||
frame_time, current_tracked_objects, motion_boxes, regions
|
||||
frame_name, frame_time, current_tracked_objects, motion_boxes, regions
|
||||
)
|
||||
|
||||
self.update_mqtt_motion(camera, frame_time, motion_boxes)
|
||||
@@ -820,6 +809,7 @@ class TrackedObjectProcessor(threading.Thread):
|
||||
self.detection_publisher.publish(
|
||||
(
|
||||
camera,
|
||||
frame_name,
|
||||
frame_time,
|
||||
tracked_objects,
|
||||
motion_boxes,
|
||||
|
||||
@@ -268,12 +268,10 @@ class BirdsEyeFrameManager:
|
||||
def __init__(
|
||||
self,
|
||||
config: FrigateConfig,
|
||||
frame_manager: SharedMemoryFrameManager,
|
||||
stop_event: mp.Event,
|
||||
):
|
||||
self.config = config
|
||||
self.mode = config.birdseye.mode
|
||||
self.frame_manager = frame_manager
|
||||
width, height = get_canvas_shape(config.birdseye.width, config.birdseye.height)
|
||||
self.frame_shape = (height, width)
|
||||
self.yuv_shape = (height * 3 // 2, width)
|
||||
@@ -351,18 +349,13 @@ class BirdsEyeFrameManager:
|
||||
logger.debug("Clearing the birdseye frame")
|
||||
self.frame[:] = self.blank_frame
|
||||
|
||||
def copy_to_position(self, position, camera=None, frame_time=None):
|
||||
def copy_to_position(self, position, camera=None, frame: np.ndarray = None):
|
||||
if camera is None:
|
||||
frame = None
|
||||
channel_dims = None
|
||||
else:
|
||||
frame_id = f"{camera}{frame_time}"
|
||||
frame = self.frame_manager.get(
|
||||
frame_id, self.config.cameras[camera].frame_shape_yuv
|
||||
)
|
||||
|
||||
if frame is None:
|
||||
logger.debug(f"Unable to copy frame {camera}{frame_time} to birdseye.")
|
||||
logger.debug(f"Unable to copy frame {camera} to birdseye.")
|
||||
return
|
||||
|
||||
channel_dims = self.cameras[camera]["channel_dims"]
|
||||
@@ -375,8 +368,6 @@ class BirdsEyeFrameManager:
|
||||
channel_dims,
|
||||
)
|
||||
|
||||
self.frame_manager.close(frame_id)
|
||||
|
||||
def camera_active(self, mode, object_box_count, motion_box_count):
|
||||
if mode == BirdseyeModeEnum.continuous:
|
||||
return True
|
||||
@@ -387,7 +378,7 @@ class BirdsEyeFrameManager:
|
||||
if mode == BirdseyeModeEnum.objects and object_box_count > 0:
|
||||
return True
|
||||
|
||||
def update_frame(self):
|
||||
def update_frame(self, frame: np.ndarray):
|
||||
"""Update to a new frame for birdseye."""
|
||||
|
||||
# determine how many cameras are tracking objects within the last inactivity_threshold seconds
|
||||
@@ -397,7 +388,7 @@ class BirdsEyeFrameManager:
|
||||
for cam, cam_data in self.cameras.items()
|
||||
if self.config.cameras[cam].birdseye.enabled
|
||||
and cam_data["last_active_frame"] > 0
|
||||
and cam_data["current_frame"] - cam_data["last_active_frame"]
|
||||
and cam_data["current_frame_time"] - cam_data["last_active_frame"]
|
||||
< self.inactivity_threshold
|
||||
]
|
||||
)
|
||||
@@ -414,7 +405,7 @@ class BirdsEyeFrameManager:
|
||||
limited_active_cameras = sorted(
|
||||
active_cameras,
|
||||
key=lambda active_camera: (
|
||||
self.cameras[active_camera]["current_frame"]
|
||||
self.cameras[active_camera]["current_frame_time"]
|
||||
- self.cameras[active_camera]["last_active_frame"]
|
||||
),
|
||||
)
|
||||
@@ -524,7 +515,9 @@ class BirdsEyeFrameManager:
|
||||
for row in self.camera_layout:
|
||||
for position in row:
|
||||
self.copy_to_position(
|
||||
position[1], position[0], self.cameras[position[0]]["current_frame"]
|
||||
position[1],
|
||||
position[0],
|
||||
self.cameras[position[0]]["current_frame"],
|
||||
)
|
||||
|
||||
return True
|
||||
@@ -672,7 +665,14 @@ class BirdsEyeFrameManager:
|
||||
else:
|
||||
return standard_candidate_layout
|
||||
|
||||
def update(self, camera, object_count, motion_count, frame_time, frame) -> bool:
|
||||
def update(
|
||||
self,
|
||||
camera: str,
|
||||
object_count: int,
|
||||
motion_count: int,
|
||||
frame_time: float,
|
||||
frame: np.ndarray,
|
||||
) -> bool:
|
||||
# don't process if birdseye is disabled for this camera
|
||||
camera_config = self.config.cameras[camera].birdseye
|
||||
|
||||
@@ -689,7 +689,8 @@ class BirdsEyeFrameManager:
|
||||
return False
|
||||
|
||||
# update the last active frame for the camera
|
||||
self.cameras[camera]["current_frame"] = frame_time
|
||||
self.cameras[camera]["current_frame"] = frame.copy()
|
||||
self.cameras[camera]["current_frame_time"] = frame_time
|
||||
if self.camera_active(camera_config.mode, object_count, motion_count):
|
||||
self.cameras[camera]["last_active_frame"] = frame_time
|
||||
|
||||
@@ -700,7 +701,7 @@ class BirdsEyeFrameManager:
|
||||
return False
|
||||
|
||||
try:
|
||||
updated_frame = self.update_frame()
|
||||
updated_frame = self.update_frame(frame)
|
||||
except Exception:
|
||||
updated_frame = False
|
||||
self.active_cameras = []
|
||||
@@ -737,12 +738,12 @@ class Birdseye:
|
||||
self.broadcaster = BroadcastThread(
|
||||
"birdseye", self.converter, websocket_server, stop_event
|
||||
)
|
||||
frame_manager = SharedMemoryFrameManager()
|
||||
self.birdseye_manager = BirdsEyeFrameManager(config, frame_manager, stop_event)
|
||||
self.birdseye_manager = BirdsEyeFrameManager(config, stop_event)
|
||||
self.config_subscriber = ConfigSubscriber("config/birdseye/")
|
||||
self.frame_manager = SharedMemoryFrameManager()
|
||||
|
||||
if config.birdseye.restream:
|
||||
self.birdseye_buffer = frame_manager.create(
|
||||
self.birdseye_buffer = self.frame_manager.create(
|
||||
"birdseye",
|
||||
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
|
||||
)
|
||||
@@ -756,7 +757,7 @@ class Birdseye:
|
||||
current_tracked_objects: list[dict[str, any]],
|
||||
motion_boxes: list[list[int]],
|
||||
frame_time: float,
|
||||
frame,
|
||||
frame: np.ndarray,
|
||||
) -> None:
|
||||
# check if there is an updated config
|
||||
while True:
|
||||
|
||||
@@ -63,6 +63,7 @@ def output_frames(
|
||||
birdseye: Optional[Birdseye] = None
|
||||
preview_recorders: dict[str, PreviewRecorder] = {}
|
||||
preview_write_times: dict[str, float] = {}
|
||||
failed_frame_requests: dict[str, int] = {}
|
||||
|
||||
move_preview_frames("cache")
|
||||
|
||||
@@ -87,19 +88,27 @@ def output_frames(
|
||||
|
||||
(
|
||||
camera,
|
||||
frame_name,
|
||||
frame_time,
|
||||
current_tracked_objects,
|
||||
motion_boxes,
|
||||
regions,
|
||||
_,
|
||||
) = data
|
||||
|
||||
frame_id = f"{camera}{frame_time}"
|
||||
|
||||
frame = frame_manager.get(frame_id, config.cameras[camera].frame_shape_yuv)
|
||||
frame = frame_manager.get(frame_name, config.cameras[camera].frame_shape_yuv)
|
||||
|
||||
if frame is None:
|
||||
logger.debug(f"Failed to get frame {frame_id} from SHM")
|
||||
logger.debug(f"Failed to get frame {frame_name} from SHM")
|
||||
failed_frame_requests[camera] = failed_frame_requests.get(camera, 0) + 1
|
||||
|
||||
if failed_frame_requests[camera] > config.cameras[camera].detect.fps:
|
||||
logger.warning(
|
||||
f"Failed to retrieve many frames for {camera} from SHM, consider increasing SHM size if this continues."
|
||||
)
|
||||
|
||||
continue
|
||||
else:
|
||||
failed_frame_requests[camera] = 0
|
||||
|
||||
# send camera frame to ffmpeg process if websockets are connected
|
||||
if any(
|
||||
@@ -134,12 +143,15 @@ def output_frames(
|
||||
# check for any cameras that are currently offline
|
||||
# and need to generate a preview
|
||||
if generated_preview:
|
||||
logger.debug(
|
||||
"Checking for offline cameras because another camera generated a preview."
|
||||
)
|
||||
for camera, time in preview_write_times.copy().items():
|
||||
if time != 0 and frame_time - time > 10:
|
||||
preview_recorders[camera].flag_offline(frame_time)
|
||||
preview_write_times[camera] = frame_time
|
||||
|
||||
frame_manager.close(frame_id)
|
||||
frame_manager.close(frame_name)
|
||||
|
||||
move_preview_frames("clips")
|
||||
|
||||
@@ -151,15 +163,15 @@ def output_frames(
|
||||
|
||||
(
|
||||
camera,
|
||||
frame_name,
|
||||
frame_time,
|
||||
current_tracked_objects,
|
||||
motion_boxes,
|
||||
regions,
|
||||
) = data
|
||||
|
||||
frame_id = f"{camera}{frame_time}"
|
||||
frame = frame_manager.get(frame_id, config.cameras[camera].frame_shape_yuv)
|
||||
frame_manager.close(frame_id)
|
||||
frame = frame_manager.get(frame_name, config.cameras[camera].frame_shape_yuv)
|
||||
frame_manager.close(frame_name)
|
||||
|
||||
detection_subscriber.stop()
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ class FFMpegConverter(threading.Thread):
|
||||
# write a PREVIEW at fps and 1 key frame per clip
|
||||
self.ffmpeg_cmd = parse_preset_hardware_acceleration_encode(
|
||||
config.ffmpeg.ffmpeg_path,
|
||||
config.ffmpeg.hwaccel_args,
|
||||
"default",
|
||||
input="-f concat -y -protocol_whitelist pipe,file -safe 0 -threads 1 -i /dev/stdin",
|
||||
output=f"-threads 1 -g {PREVIEW_KEYFRAME_INTERVAL} -bf 0 -b:v {PREVIEW_QUALITY_BIT_RATES[self.config.record.preview.quality]} {FPS_VFR_PARAM} -movflags +faststart -pix_fmt yuv420p {self.path}",
|
||||
type=EncodeTypeEnum.preview,
|
||||
@@ -154,6 +154,7 @@ class PreviewRecorder:
|
||||
self.start_time = 0
|
||||
self.last_output_time = 0
|
||||
self.output_frames = []
|
||||
|
||||
if config.detect.width > config.detect.height:
|
||||
self.out_height = PREVIEW_HEIGHT
|
||||
self.out_width = (
|
||||
@@ -274,7 +275,7 @@ class PreviewRecorder:
|
||||
|
||||
return False
|
||||
|
||||
def write_frame_to_cache(self, frame_time: float, frame) -> None:
|
||||
def write_frame_to_cache(self, frame_time: float, frame: np.ndarray) -> None:
|
||||
# resize yuv frame
|
||||
small_frame = np.zeros((self.out_height * 3 // 2, self.out_width), np.uint8)
|
||||
copy_yuv_to_position(
|
||||
@@ -303,7 +304,7 @@ class PreviewRecorder:
|
||||
current_tracked_objects: list[dict[str, any]],
|
||||
motion_boxes: list[list[int]],
|
||||
frame_time: float,
|
||||
frame,
|
||||
frame: np.ndarray,
|
||||
) -> bool:
|
||||
# check for updated record config
|
||||
_, updated_record_config = self.config_subscriber.check_for_update()
|
||||
@@ -332,6 +333,10 @@ class PreviewRecorder:
|
||||
self.output_frames,
|
||||
self.requestor,
|
||||
).start()
|
||||
else:
|
||||
logger.debug(
|
||||
f"Not saving preview for {self.config.name} because there are no saved frames."
|
||||
)
|
||||
|
||||
# reset frame cache
|
||||
self.segment_end = (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user