mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-08-02 09:02:15 +03:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8033590dcb | ||
|
|
d982b3a782 | ||
|
|
d036061e3f | ||
|
|
5003ab895c |
+36
-16
@@ -1,7 +1,9 @@
|
||||
"""Preview apis."""
|
||||
|
||||
import bisect
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytz
|
||||
@@ -133,6 +135,32 @@ def preview_hour(
|
||||
return preview_ts(camera_name, start_ts, end_ts, allowed_cameras)
|
||||
|
||||
|
||||
# cache one sorted listing of the shared preview_frames dir
|
||||
_preview_listing_lock = threading.Lock()
|
||||
_preview_listing_cache: tuple[float, list[str]] = (-1.0, [])
|
||||
|
||||
|
||||
def _get_preview_frame_listing(preview_dir: str) -> list[str]:
|
||||
"""Return the sorted preview_frames listing, cached until the dir changes."""
|
||||
global _preview_listing_cache
|
||||
|
||||
# mtime bumps when a frame is added or removed, invalidating the cache
|
||||
mtime = os.stat(preview_dir).st_mtime
|
||||
cached_mtime, files = _preview_listing_cache
|
||||
if mtime == cached_mtime:
|
||||
return files
|
||||
|
||||
with _preview_listing_lock:
|
||||
# another thread may have refreshed the cache while we waited
|
||||
cached_mtime, files = _preview_listing_cache
|
||||
if mtime == cached_mtime:
|
||||
return files
|
||||
|
||||
files = sorted(entry.name for entry in os.scandir(preview_dir))
|
||||
_preview_listing_cache = (mtime, files)
|
||||
return files
|
||||
|
||||
|
||||
@router.get(
|
||||
"/preview/{camera_name}/start/{start_ts}/end/{end_ts}/frames",
|
||||
response_model=PreviewFramesResponse,
|
||||
@@ -149,23 +177,15 @@ def get_preview_frames_from_cache(camera_name: str, start_ts: float, end_ts: flo
|
||||
start_file = f"{file_start}{start_ts}.{PREVIEW_FRAME_TYPE}"
|
||||
end_file = f"{file_start}{end_ts}.{PREVIEW_FRAME_TYPE}"
|
||||
|
||||
camera_files = [
|
||||
entry.name
|
||||
for entry in os.scandir(preview_dir)
|
||||
if entry.name.startswith(file_start)
|
||||
files = _get_preview_frame_listing(preview_dir)
|
||||
|
||||
# a camera's frames form a contiguous slice of the sorted listing;
|
||||
# bisect locates it without scanning the whole directory
|
||||
left = bisect.bisect_left(files, start_file)
|
||||
right = bisect.bisect_right(files, end_file)
|
||||
selected_previews = [
|
||||
file for file in files[left:right] if file.startswith(file_start)
|
||||
]
|
||||
camera_files.sort()
|
||||
|
||||
selected_previews = []
|
||||
|
||||
for file in camera_files:
|
||||
if file < start_file:
|
||||
continue
|
||||
|
||||
if file > end_file:
|
||||
break
|
||||
|
||||
selected_previews.append(file)
|
||||
|
||||
return JSONResponse(
|
||||
content=selected_previews,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Tests for frigate.util.builtin helpers."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from frigate.util.builtin import EventsPerSecond
|
||||
|
||||
|
||||
class TestEventsPerSecond(unittest.TestCase):
|
||||
def test_eps_is_zero_before_any_events(self) -> None:
|
||||
eps = EventsPerSecond()
|
||||
with patch("frigate.util.builtin.time.monotonic", return_value=100.0):
|
||||
self.assertEqual(eps.eps(), 0.0)
|
||||
|
||||
def test_eps_counts_events_in_window(self) -> None:
|
||||
eps = EventsPerSecond(last_n_seconds=10)
|
||||
clock = [1000.0]
|
||||
with patch("frigate.util.builtin.time.monotonic", side_effect=lambda: clock[0]):
|
||||
eps.start()
|
||||
# one event per second for five seconds
|
||||
for _ in range(5):
|
||||
clock[0] += 1.0
|
||||
eps.update()
|
||||
# five events over the five seconds since start
|
||||
self.assertAlmostEqual(eps.eps(), 1.0)
|
||||
|
||||
def test_old_timestamps_expire_from_window(self) -> None:
|
||||
eps = EventsPerSecond(last_n_seconds=10)
|
||||
clock = [0.0]
|
||||
with patch("frigate.util.builtin.time.monotonic", side_effect=lambda: clock[0]):
|
||||
eps.start()
|
||||
for _ in range(10):
|
||||
clock[0] += 1.0
|
||||
eps.update()
|
||||
# jump well past the window so every timestamp ages out
|
||||
clock[0] += 100.0
|
||||
self.assertEqual(eps.eps(), 0.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import datetime
|
||||
import logging
|
||||
import math
|
||||
import multiprocessing.queues
|
||||
@@ -10,7 +9,9 @@ import queue
|
||||
import re
|
||||
import shlex
|
||||
import struct
|
||||
import time
|
||||
import urllib.parse
|
||||
from collections import deque
|
||||
from collections.abc import Mapping
|
||||
from multiprocessing.managers import ValueProxy
|
||||
from pathlib import Path
|
||||
@@ -32,23 +33,20 @@ class EventsPerSecond:
|
||||
self._start = None
|
||||
self._max_events = max_events
|
||||
self._last_n_seconds = last_n_seconds
|
||||
self._timestamps = []
|
||||
self._timestamps: deque[float] = deque(maxlen=max_events)
|
||||
|
||||
def start(self) -> None:
|
||||
self._start = datetime.datetime.now().timestamp()
|
||||
self._start = time.monotonic()
|
||||
|
||||
def update(self) -> None:
|
||||
now = datetime.datetime.now().timestamp()
|
||||
now = time.monotonic()
|
||||
if self._start is None:
|
||||
self._start = now
|
||||
self._timestamps.append(now)
|
||||
# truncate the list when it goes 100 over the max_size
|
||||
if len(self._timestamps) > self._max_events + 100:
|
||||
self._timestamps = self._timestamps[(1 - self._max_events) :]
|
||||
self.expire_timestamps(now)
|
||||
|
||||
def eps(self) -> float:
|
||||
now = datetime.datetime.now().timestamp()
|
||||
now = time.monotonic()
|
||||
if self._start is None:
|
||||
self._start = now
|
||||
# compute the (approximate) events in the last n seconds
|
||||
@@ -63,7 +61,7 @@ class EventsPerSecond:
|
||||
def expire_timestamps(self, now: float) -> None:
|
||||
threshold = now - self._last_n_seconds
|
||||
while self._timestamps and self._timestamps[0] < threshold:
|
||||
del self._timestamps[0]
|
||||
self._timestamps.popleft()
|
||||
|
||||
|
||||
class InferenceSpeed:
|
||||
|
||||
Generated
+8
-8
@@ -8136,16 +8136,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
|
||||
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
|
||||
"integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"es-set-tostringtag": "^2.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"mime-types": "^2.1.12"
|
||||
"hasown": "^2.0.4",
|
||||
"mime-types": "^2.1.35"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
@@ -8492,9 +8492,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
|
||||
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
|
||||
@@ -70,6 +70,13 @@
|
||||
"selectFromTimeline": "Select from Timeline",
|
||||
"cameraSelection": "Cameras",
|
||||
"cameraSelectionHelp": "Cameras with tracked objects in this time range are pre-selected",
|
||||
"searchOrSelectGroup": "Search, or select a camera group...",
|
||||
"selectAll": "Select all cameras",
|
||||
"clearSelection": "Clear selection",
|
||||
"selectWithActivity": "Cameras with tracked objects",
|
||||
"selectGroup": "Select group",
|
||||
"noMatchingCameras": "No cameras match your search",
|
||||
"selectedCount": "{{selected}} / {{total}} selected",
|
||||
"checkingActivity": "Checking camera activity...",
|
||||
"noCameras": "No cameras available",
|
||||
"detectionCount_one": "1 tracked object",
|
||||
|
||||
@@ -39,6 +39,16 @@ import {
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import {
|
||||
Command,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "../ui/command";
|
||||
import { IconRenderer } from "../icons/IconPicker";
|
||||
import * as LuIcons from "react-icons/lu";
|
||||
import { isDesktop, isMobile } from "react-device-detect";
|
||||
import { Drawer, DrawerContent, DrawerTrigger } from "../ui/drawer";
|
||||
import SaveExportOverlay from "./SaveExportOverlay";
|
||||
@@ -376,6 +386,9 @@ export function ExportContent({
|
||||
const [newCaseName, setNewCaseName] = useState("");
|
||||
const [newCaseDescription, setNewCaseDescription] = useState("");
|
||||
const [isStartingBatchExport, setIsStartingBatchExport] = useState(false);
|
||||
const [cameraSearch, setCameraSearch] = useState("");
|
||||
const [cameraMenuOpen, setCameraMenuOpen] = useState(false);
|
||||
const cameraMenuRef = useRef<HTMLDivElement>(null);
|
||||
const multiRangeKey = useMemo(() => {
|
||||
if (activeTab !== "multi" || !range) {
|
||||
return undefined;
|
||||
@@ -577,6 +590,75 @@ export function ExportContent({
|
||||
);
|
||||
}, []);
|
||||
|
||||
const availableCameraIds = useMemo(
|
||||
() => cameraActivities.map((activity) => activity.camera),
|
||||
[cameraActivities],
|
||||
);
|
||||
|
||||
const activeCameraIds = useMemo(
|
||||
() =>
|
||||
cameraActivities
|
||||
.filter((activity) => activity.hasDetections)
|
||||
.map((activity) => activity.camera),
|
||||
[cameraActivities],
|
||||
);
|
||||
|
||||
const cameraGroups = useMemo(
|
||||
() =>
|
||||
Object.entries(config?.camera_groups ?? {})
|
||||
.map(([name, group]) => ({
|
||||
name,
|
||||
icon: group.icon,
|
||||
order: group.order,
|
||||
cameras: group.cameras.filter((cameraId) =>
|
||||
availableCameraIds.includes(cameraId),
|
||||
),
|
||||
}))
|
||||
.filter((group) => group.cameras.length > 0)
|
||||
.sort((a, b) => a.order - b.order),
|
||||
[config?.camera_groups, availableCameraIds],
|
||||
);
|
||||
|
||||
// Filter the rendered camera cards by the search query
|
||||
const filteredCameraActivities = useMemo(() => {
|
||||
const query = cameraSearch.trim().toLowerCase();
|
||||
if (!query) {
|
||||
return cameraActivities;
|
||||
}
|
||||
return cameraActivities.filter((activity) => {
|
||||
const friendlyName = resolveCameraName(config, activity.camera);
|
||||
return (
|
||||
activity.camera.toLowerCase().includes(query) ||
|
||||
friendlyName.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
}, [cameraActivities, cameraSearch, config]);
|
||||
|
||||
// Group/all/activity selection replaces the current selection
|
||||
const applyCameraSelection = useCallback((cameraIds: string[]) => {
|
||||
setHasManualCameraSelection(true);
|
||||
setSelectedCameraIds(cameraIds);
|
||||
setCameraMenuOpen(false);
|
||||
}, []);
|
||||
|
||||
// Close the dropdown when focus leaves the camera selection control entirely
|
||||
const handleCameraInputBlur = useCallback((event: React.FocusEvent) => {
|
||||
if (
|
||||
cameraMenuRef.current &&
|
||||
!cameraMenuRef.current.contains(event.relatedTarget as Node)
|
||||
) {
|
||||
setCameraMenuOpen(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Reset the search and dropdown when leaving the multi-camera tab
|
||||
useEffect(() => {
|
||||
if (activeTab !== "multi") {
|
||||
setCameraSearch("");
|
||||
setCameraMenuOpen(false);
|
||||
}
|
||||
}, [activeTab]);
|
||||
|
||||
const startBatchExport = useCallback(async () => {
|
||||
if (isStartingBatchExport) {
|
||||
return;
|
||||
@@ -802,7 +884,7 @@ export function ExportContent({
|
||||
|
||||
{isAdmin && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-secondary-foreground">
|
||||
<Label className="text-sm text-primary">
|
||||
{t("export.case.label")}
|
||||
</Label>
|
||||
<Select
|
||||
@@ -859,7 +941,7 @@ export function ExportContent({
|
||||
)}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-secondary-foreground">
|
||||
<Label className="text-sm text-primary">
|
||||
{t("export.multiCamera.timeRange")}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -902,16 +984,109 @@ export function ExportContent({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-secondary-foreground">
|
||||
{t("export.multiCamera.cameraSelection")}
|
||||
</Label>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Label className="text-sm text-primary">
|
||||
{t("export.multiCamera.cameraSelection")}
|
||||
</Label>
|
||||
{availableCameraIds.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("export.multiCamera.selectedCount", {
|
||||
selected: selectedCameraCount,
|
||||
total: availableCameraIds.length,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{t("export.multiCamera.cameraSelectionHelp")}
|
||||
</div>
|
||||
{!isEventsLoading && availableCameraIds.length > 0 && (
|
||||
<div className="relative" ref={cameraMenuRef}>
|
||||
<Command
|
||||
shouldFilter={false}
|
||||
className="overflow-visible rounded-md border bg-secondary/40"
|
||||
>
|
||||
<CommandInput
|
||||
value={cameraSearch}
|
||||
onValueChange={setCameraSearch}
|
||||
onFocus={() => setCameraMenuOpen(true)}
|
||||
onBlur={handleCameraInputBlur}
|
||||
placeholder={t("export.multiCamera.searchOrSelectGroup")}
|
||||
/>
|
||||
{/* Hide the actions/groups menu while a search query is
|
||||
active so it doesn't cover the filtered camera cards. */}
|
||||
{cameraMenuOpen && cameraSearch.trim().length === 0 && (
|
||||
<CommandList className="absolute top-full z-10 mt-1 max-h-72 w-full rounded-md border bg-background shadow-md">
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
value="action:select-all"
|
||||
className="cursor-pointer"
|
||||
onSelect={() =>
|
||||
applyCameraSelection(availableCameraIds)
|
||||
}
|
||||
>
|
||||
<span>{t("export.multiCamera.selectAll")}</span>
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{availableCameraIds.length}
|
||||
</span>
|
||||
</CommandItem>
|
||||
<CommandItem
|
||||
value="action:clear"
|
||||
className="cursor-pointer"
|
||||
onSelect={() => applyCameraSelection([])}
|
||||
>
|
||||
{t("export.multiCamera.clearSelection")}
|
||||
</CommandItem>
|
||||
<CommandItem
|
||||
value="action:activity"
|
||||
className="cursor-pointer"
|
||||
onSelect={() => applyCameraSelection(activeCameraIds)}
|
||||
>
|
||||
<span>
|
||||
{t("export.multiCamera.selectWithActivity")}
|
||||
</span>
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{activeCameraIds.length}
|
||||
</span>
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
{cameraGroups.length > 0 && (
|
||||
<>
|
||||
<CommandSeparator />
|
||||
<CommandGroup
|
||||
heading={t("export.multiCamera.selectGroup")}
|
||||
>
|
||||
{cameraGroups.map((group) => (
|
||||
<CommandItem
|
||||
key={group.name}
|
||||
value={`group:${group.name}`}
|
||||
className="cursor-pointer"
|
||||
onSelect={() =>
|
||||
applyCameraSelection(group.cameras)
|
||||
}
|
||||
>
|
||||
<IconRenderer
|
||||
icon={LuIcons[group.icon]}
|
||||
className="mr-2 size-4 text-secondary-foreground"
|
||||
/>
|
||||
<span className="truncate">{group.name}</span>
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{group.cameras.length}
|
||||
</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</>
|
||||
)}
|
||||
</CommandList>
|
||||
)}
|
||||
</Command>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
"scrollbar-container space-y-2",
|
||||
isDesktop && "max-h-64 overflow-y-auto pr-1",
|
||||
isDesktop && "max-h-64 overflow-y-auto p-0.5 pr-1",
|
||||
)}
|
||||
>
|
||||
{isEventsLoading && (
|
||||
@@ -924,7 +1099,14 @@ export function ExportContent({
|
||||
{t("export.multiCamera.noCameras")}
|
||||
</div>
|
||||
)}
|
||||
{cameraActivities.map((activity) => {
|
||||
{!isEventsLoading &&
|
||||
cameraActivities.length > 0 &&
|
||||
filteredCameraActivities.length === 0 && (
|
||||
<div className="px-2 py-4 text-sm text-muted-foreground">
|
||||
{t("export.multiCamera.noMatchingCameras")}
|
||||
</div>
|
||||
)}
|
||||
{filteredCameraActivities.map((activity) => {
|
||||
const isSelected = selectedCameraIds.includes(activity.camera);
|
||||
|
||||
return (
|
||||
@@ -981,7 +1163,7 @@ export function ExportContent({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-secondary-foreground">
|
||||
<Label className="text-sm text-primary">
|
||||
{t("export.multiCamera.nameLabel")}
|
||||
</Label>
|
||||
<Input
|
||||
@@ -994,7 +1176,7 @@ export function ExportContent({
|
||||
|
||||
{isAdmin && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-secondary-foreground">
|
||||
<Label className="text-sm text-primary">
|
||||
{t("export.case.label")}
|
||||
</Label>
|
||||
<Select
|
||||
|
||||
Reference in New Issue
Block a user