mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-02-18 17:14:26 +03:00
Enable UI for feature metrics
This commit is contained in:
parent
ccf8848143
commit
d578fceac8
@ -235,7 +235,9 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
|
|
||||||
if self.lpr_config.enabled:
|
if self.lpr_config.enabled:
|
||||||
start = datetime.datetime.now().timestamp()
|
start = datetime.datetime.now().timestamp()
|
||||||
self._process_license_plate(data, yuv_frame)
|
processed = self._process_license_plate(data, yuv_frame)
|
||||||
|
|
||||||
|
if processed:
|
||||||
duration = datetime.datetime.now().timestamp() - start
|
duration = datetime.datetime.now().timestamp() - start
|
||||||
self.metrics.alpr_pps.value = (
|
self.metrics.alpr_pps.value = (
|
||||||
self.metrics.alpr_pps.value * 9 + duration
|
self.metrics.alpr_pps.value * 9 + duration
|
||||||
@ -558,19 +560,19 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
|
|
||||||
def _process_license_plate(
|
def _process_license_plate(
|
||||||
self, obj_data: dict[str, any], frame: np.ndarray
|
self, obj_data: dict[str, any], frame: np.ndarray
|
||||||
) -> None:
|
) -> bool:
|
||||||
"""Look for license plates in image."""
|
"""Look for license plates in image."""
|
||||||
id = obj_data["id"]
|
id = obj_data["id"]
|
||||||
|
|
||||||
# don't run for non car objects
|
# don't run for non car objects
|
||||||
if obj_data.get("label") != "car":
|
if obj_data.get("label") != "car":
|
||||||
logger.debug("Not a processing license plate for non car object.")
|
logger.debug("Not a processing license plate for non car object.")
|
||||||
return
|
return False
|
||||||
|
|
||||||
# don't run for stationary car objects
|
# don't run for stationary car objects
|
||||||
if obj_data.get("stationary") == True:
|
if obj_data.get("stationary") == True:
|
||||||
logger.debug("Not a processing license plate for a stationary car object.")
|
logger.debug("Not a processing license plate for a stationary car object.")
|
||||||
return
|
return False
|
||||||
|
|
||||||
# don't overwrite sub label for objects that have a sub label
|
# don't overwrite sub label for objects that have a sub label
|
||||||
# that is not a license plate
|
# that is not a license plate
|
||||||
@ -578,7 +580,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
logger.debug(
|
logger.debug(
|
||||||
f"Not processing license plate due to existing sub label: {obj_data.get('sub_label')}."
|
f"Not processing license plate due to existing sub label: {obj_data.get('sub_label')}."
|
||||||
)
|
)
|
||||||
return
|
return False
|
||||||
|
|
||||||
license_plate: Optional[dict[str, any]] = None
|
license_plate: Optional[dict[str, any]] = None
|
||||||
|
|
||||||
@ -587,7 +589,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
car_box = obj_data.get("box")
|
car_box = obj_data.get("box")
|
||||||
|
|
||||||
if not car_box:
|
if not car_box:
|
||||||
return None
|
return False
|
||||||
|
|
||||||
rgb = cv2.cvtColor(frame, cv2.COLOR_YUV2RGB_I420)
|
rgb = cv2.cvtColor(frame, cv2.COLOR_YUV2RGB_I420)
|
||||||
left, top, right, bottom = car_box
|
left, top, right, bottom = car_box
|
||||||
@ -596,7 +598,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
|
|
||||||
if not license_plate:
|
if not license_plate:
|
||||||
logger.debug("Detected no license plates for car object.")
|
logger.debug("Detected no license plates for car object.")
|
||||||
return
|
return False
|
||||||
|
|
||||||
license_plate_frame = car[
|
license_plate_frame = car[
|
||||||
license_plate[1] : license_plate[3], license_plate[0] : license_plate[2]
|
license_plate[1] : license_plate[3], license_plate[0] : license_plate[2]
|
||||||
@ -606,7 +608,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
# don't run for object without attributes
|
# don't run for object without attributes
|
||||||
if not obj_data.get("current_attributes"):
|
if not obj_data.get("current_attributes"):
|
||||||
logger.debug("No attributes to parse.")
|
logger.debug("No attributes to parse.")
|
||||||
return
|
return False
|
||||||
|
|
||||||
attributes: list[dict[str, any]] = obj_data.get("current_attributes", [])
|
attributes: list[dict[str, any]] = obj_data.get("current_attributes", [])
|
||||||
for attr in attributes:
|
for attr in attributes:
|
||||||
@ -620,7 +622,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
|
|
||||||
# no license plates detected in this frame
|
# no license plates detected in this frame
|
||||||
if not license_plate:
|
if not license_plate:
|
||||||
return
|
return False
|
||||||
|
|
||||||
license_plate_box = license_plate.get("box")
|
license_plate_box = license_plate.get("box")
|
||||||
|
|
||||||
@ -630,7 +632,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
or area(license_plate_box) < self.config.lpr.min_area
|
or area(license_plate_box) < self.config.lpr.min_area
|
||||||
):
|
):
|
||||||
logger.debug(f"Invalid license plate box {license_plate}")
|
logger.debug(f"Invalid license plate box {license_plate}")
|
||||||
return
|
return False
|
||||||
|
|
||||||
license_plate_frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
|
license_plate_frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
|
||||||
license_plate_frame = license_plate_frame[
|
license_plate_frame = license_plate_frame[
|
||||||
@ -659,7 +661,7 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
else:
|
else:
|
||||||
# no plates found
|
# no plates found
|
||||||
logger.debug("No text detected")
|
logger.debug("No text detected")
|
||||||
return
|
return True
|
||||||
|
|
||||||
top_plate, top_char_confidences, top_area = (
|
top_plate, top_char_confidences, top_area = (
|
||||||
license_plates[0],
|
license_plates[0],
|
||||||
@ -705,14 +707,14 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
f"length={len(top_plate)}, avg_conf={avg_confidence:.2f}, area={top_area} "
|
f"length={len(top_plate)}, avg_conf={avg_confidence:.2f}, area={top_area} "
|
||||||
f"vs Previous: length={len(prev_plate)}, avg_conf={prev_avg_confidence:.2f}, area={prev_area}"
|
f"vs Previous: length={len(prev_plate)}, avg_conf={prev_avg_confidence:.2f}, area={prev_area}"
|
||||||
)
|
)
|
||||||
return
|
return True
|
||||||
|
|
||||||
# Check against minimum confidence threshold
|
# Check against minimum confidence threshold
|
||||||
if avg_confidence < self.lpr_config.threshold:
|
if avg_confidence < self.lpr_config.threshold:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Average confidence {avg_confidence} is less than threshold ({self.lpr_config.threshold})"
|
f"Average confidence {avg_confidence} is less than threshold ({self.lpr_config.threshold})"
|
||||||
)
|
)
|
||||||
return
|
return True
|
||||||
|
|
||||||
# Determine subLabel based on known plates, use regex matching
|
# Determine subLabel based on known plates, use regex matching
|
||||||
# Default to the detected plate, use label name if there's a match
|
# Default to the detected plate, use label name if there's a match
|
||||||
@ -742,6 +744,8 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
"area": top_area,
|
"area": top_area,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
def _create_thumbnail(self, yuv_frame, box, height=500) -> Optional[bytes]:
|
def _create_thumbnail(self, yuv_frame, box, height=500) -> Optional[bytes]:
|
||||||
"""Return jpg thumbnail of a region of the frame."""
|
"""Return jpg thumbnail of a region of the frame."""
|
||||||
frame = cv2.cvtColor(yuv_frame, cv2.COLOR_YUV2BGR_I420)
|
frame = cv2.cvtColor(yuv_frame, cv2.COLOR_YUV2BGR_I420)
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
import { FrigateStats } from "@/types/stats";
|
import { FrigateStats } from "@/types/stats";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import TimeAgo from "@/components/dynamic/TimeAgo";
|
import TimeAgo from "@/components/dynamic/TimeAgo";
|
||||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||||
import { isDesktop, isMobile } from "react-device-detect";
|
import { isDesktop, isMobile } from "react-device-detect";
|
||||||
import GeneralMetrics from "@/views/system/GeneralMetrics";
|
import GeneralMetrics from "@/views/system/GeneralMetrics";
|
||||||
import StorageMetrics from "@/views/system/StorageMetrics";
|
import StorageMetrics from "@/views/system/StorageMetrics";
|
||||||
import { LuActivity, LuHardDrive } from "react-icons/lu";
|
import { LuActivity, LuHardDrive, LuSearchCode } from "react-icons/lu";
|
||||||
import { FaVideo } from "react-icons/fa";
|
import { FaVideo } from "react-icons/fa";
|
||||||
import Logo from "@/components/Logo";
|
import Logo from "@/components/Logo";
|
||||||
import useOptimisticState from "@/hooks/use-optimistic-state";
|
import useOptimisticState from "@/hooks/use-optimistic-state";
|
||||||
@ -14,11 +14,28 @@ import CameraMetrics from "@/views/system/CameraMetrics";
|
|||||||
import { useHashState } from "@/hooks/use-overlay-state";
|
import { useHashState } from "@/hooks/use-overlay-state";
|
||||||
import { capitalizeFirstLetter } from "@/utils/stringUtil";
|
import { capitalizeFirstLetter } from "@/utils/stringUtil";
|
||||||
import { Toaster } from "@/components/ui/sonner";
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
|
import { FrigateConfig } from "@/types/frigateConfig";
|
||||||
|
import FeatureMetrics from "@/views/system/FeatureMetrics";
|
||||||
|
|
||||||
const metrics = ["general", "storage", "cameras"] as const;
|
const allMetrics = ["general", "features", "storage", "cameras"] as const;
|
||||||
type SystemMetric = (typeof metrics)[number];
|
type SystemMetric = (typeof allMetrics)[number];
|
||||||
|
|
||||||
function System() {
|
function System() {
|
||||||
|
const { data: config } = useSWR<FrigateConfig>("config", {
|
||||||
|
revalidateOnFocus: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const metrics = useMemo(() => {
|
||||||
|
const metrics = [...allMetrics];
|
||||||
|
|
||||||
|
if (!config?.semantic_search.enabled) {
|
||||||
|
const index = metrics.indexOf("features");
|
||||||
|
metrics.splice(index, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return metrics;
|
||||||
|
}, [config]);
|
||||||
|
|
||||||
// stats page
|
// stats page
|
||||||
|
|
||||||
const [page, setPage] = useHashState<SystemMetric>();
|
const [page, setPage] = useHashState<SystemMetric>();
|
||||||
@ -67,6 +84,7 @@ function System() {
|
|||||||
aria-label={`Select ${item}`}
|
aria-label={`Select ${item}`}
|
||||||
>
|
>
|
||||||
{item == "general" && <LuActivity className="size-4" />}
|
{item == "general" && <LuActivity className="size-4" />}
|
||||||
|
{item == "features" && <LuSearchCode className="size-4" />}
|
||||||
{item == "storage" && <LuHardDrive className="size-4" />}
|
{item == "storage" && <LuHardDrive className="size-4" />}
|
||||||
{item == "cameras" && <FaVideo className="size-4" />}
|
{item == "cameras" && <FaVideo className="size-4" />}
|
||||||
{isDesktop && <div className="capitalize">{item}</div>}
|
{isDesktop && <div className="capitalize">{item}</div>}
|
||||||
@ -96,6 +114,12 @@ function System() {
|
|||||||
setLastUpdated={setLastUpdated}
|
setLastUpdated={setLastUpdated}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{page == "features" && (
|
||||||
|
<FeatureMetrics
|
||||||
|
lastUpdated={lastUpdated}
|
||||||
|
setLastUpdated={setLastUpdated}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{page == "storage" && <StorageMetrics setLastUpdated={setLastUpdated} />}
|
{page == "storage" && <StorageMetrics setLastUpdated={setLastUpdated} />}
|
||||||
{page == "cameras" && (
|
{page == "cameras" && (
|
||||||
<CameraMetrics
|
<CameraMetrics
|
||||||
|
|||||||
@ -2,6 +2,7 @@ export interface FrigateStats {
|
|||||||
cameras: { [camera_name: string]: CameraStats };
|
cameras: { [camera_name: string]: CameraStats };
|
||||||
cpu_usages: { [pid: string]: CpuStats };
|
cpu_usages: { [pid: string]: CpuStats };
|
||||||
detectors: { [detectorKey: string]: DetectorStats };
|
detectors: { [detectorKey: string]: DetectorStats };
|
||||||
|
embeddings?: EmbeddingsStats;
|
||||||
gpu_usages?: { [gpuKey: string]: GpuStats };
|
gpu_usages?: { [gpuKey: string]: GpuStats };
|
||||||
processes: { [processKey: string]: ExtraProcessStats };
|
processes: { [processKey: string]: ExtraProcessStats };
|
||||||
service: ServiceStats;
|
service: ServiceStats;
|
||||||
@ -34,6 +35,13 @@ export type DetectorStats = {
|
|||||||
pid: number;
|
pid: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type EmbeddingsStats = {
|
||||||
|
image_embedding_speed: number;
|
||||||
|
face_embedding_speed: number;
|
||||||
|
plate_recognition_speed: number;
|
||||||
|
text_embedding_speed: number;
|
||||||
|
};
|
||||||
|
|
||||||
export type ExtraProcessStats = {
|
export type ExtraProcessStats = {
|
||||||
pid: number;
|
pid: number;
|
||||||
};
|
};
|
||||||
|
|||||||
122
web/src/views/system/FeatureMetrics.tsx
Normal file
122
web/src/views/system/FeatureMetrics.tsx
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
import useSWR from "swr";
|
||||||
|
import { FrigateStats } from "@/types/stats";
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { useFrigateStats } from "@/api/ws";
|
||||||
|
import { InferenceThreshold } from "@/types/graph";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { ThresholdBarGraph } from "@/components/graph/SystemGraph";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type FeatureMetricsProps = {
|
||||||
|
lastUpdated: number;
|
||||||
|
setLastUpdated: (last: number) => void;
|
||||||
|
};
|
||||||
|
export default function FeatureMetrics({
|
||||||
|
lastUpdated,
|
||||||
|
setLastUpdated,
|
||||||
|
}: FeatureMetricsProps) {
|
||||||
|
// stats
|
||||||
|
|
||||||
|
const { data: initialStats } = useSWR<FrigateStats[]>(
|
||||||
|
["stats/history", { keys: "embeddings,service" }],
|
||||||
|
{
|
||||||
|
revalidateOnFocus: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const [statsHistory, setStatsHistory] = useState<FrigateStats[]>([]);
|
||||||
|
const updatedStats = useFrigateStats();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (initialStats == undefined || initialStats.length == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statsHistory.length == 0) {
|
||||||
|
setStatsHistory(initialStats);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!updatedStats) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updatedStats.service.last_updated > lastUpdated) {
|
||||||
|
setStatsHistory([...statsHistory.slice(1), updatedStats]);
|
||||||
|
setLastUpdated(Date.now() / 1000);
|
||||||
|
}
|
||||||
|
}, [initialStats, updatedStats, statsHistory, lastUpdated, setLastUpdated]);
|
||||||
|
|
||||||
|
// timestamps
|
||||||
|
|
||||||
|
const updateTimes = useMemo(
|
||||||
|
() => statsHistory.map((stats) => stats.service.last_updated),
|
||||||
|
[statsHistory],
|
||||||
|
);
|
||||||
|
|
||||||
|
// features stats
|
||||||
|
|
||||||
|
const embeddingInferenceTimeSeries = useMemo(() => {
|
||||||
|
if (!statsHistory) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const series: {
|
||||||
|
[key: string]: { name: string; data: { x: number; y: number }[] };
|
||||||
|
} = {};
|
||||||
|
|
||||||
|
statsHistory.forEach((stats, statsIdx) => {
|
||||||
|
if (!stats?.embeddings) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(stats.embeddings).forEach(([rawKey, stat]) => {
|
||||||
|
const key = rawKey.replaceAll("_", " ");
|
||||||
|
|
||||||
|
if (!(key in series)) {
|
||||||
|
series[key] = { name: key, data: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
series[key].data.push({ x: statsIdx + 1, y: stat });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return Object.values(series);
|
||||||
|
}, [statsHistory]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="scrollbar-container mt-4 flex size-full flex-col overflow-y-auto">
|
||||||
|
<div className="text-sm font-medium text-muted-foreground">
|
||||||
|
Features
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"mt-4 grid w-full grid-cols-1 gap-2 sm:grid-cols-3",
|
||||||
|
embeddingInferenceTimeSeries && "sm:grid-cols-4",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{statsHistory.length != 0 ? (
|
||||||
|
<>
|
||||||
|
{embeddingInferenceTimeSeries.map((series) => (
|
||||||
|
<div className="rounded-lg bg-background_alt p-2.5 md:rounded-2xl">
|
||||||
|
<div className="mb-5 capitalize">{series.name}</div>
|
||||||
|
<ThresholdBarGraph
|
||||||
|
key={series.name}
|
||||||
|
graphId={`${series.name}-inference`}
|
||||||
|
name={series.name}
|
||||||
|
unit="ms"
|
||||||
|
threshold={InferenceThreshold}
|
||||||
|
updateTimes={updateTimes}
|
||||||
|
data={[series]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Skeleton className="aspect-video w-full rounded-lg md:rounded-2xl" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user