mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-07-27 22:29:02 +03:00
Merge detector and model in settings UI (#23216)
* add embedded mode to BaseSection so parents can host the save action * add optional action slot to current Frigate+ model summary * add w-full to action slot flex wrapper for explicit width contract * i18n * merged detectors and model settings view * fix document title * Embed detector form in merged settings view * add detection model card with tabs and custom model embed * add Frigate+ model selector with filter popover to merged page * Add mismatch banner and gate save on detector and model compatibility * Wire atomic save, restart toast, and undo on detectors and model page * Clear child pending data on undo * route merged detectors and model view in settings * trim Frigate+ page to account-only and remove old detection model view * basic e2e * Fix unsaved-changes guard, custom path leak, and post-failure cache resync * Rename to Detectors and model, float Modified badge, use ConfigMessageBanner for mismatch * Hide Plus/Custom tabs when Frigate+ is not enabled * Detect active Plus model via model.plus.id instead of path prefix * Sync state back to snapshot when child form un-modifies and remount on undo * Always require restart on save since model changes also need one * Wrap Frigate+ model selector in SplitCardRow with label and description * rename tab * update docs * sync top-level model with default detector's resolved model when the user doesn't define a top-level `model:` block, `FrigateConfig.model` stayed at pydantic field defaults (320×320, /labelmap.txt) while the per-detector model picked up `DEFAULT_MODEL` for openvino on cpu (300×300, coco_91cl_bkgr.txt introduced in #23127), causing `RemoteObjectDetector` to fail with "buffer is too small for requested array" because the SHM was sized from the per-detector model but mapped using the top-level one. After the detector loop, copy the first detector's resolved model up to `self.model` so both sides agree on dimensions and labelmap * revert to cpu detector by default use openvino cpu for new configs only * add defaults
This commit is contained in:
@@ -44,7 +44,7 @@ export function ConfigMessageBanner({ messages }: ConfigMessageBannerProps) {
|
||||
className="flex items-center [&>svg+div]:translate-y-0 [&>svg]:static [&>svg~*]:pl-2"
|
||||
>
|
||||
<SeverityIcon severity={msg.severity} />
|
||||
<AlertDescription>{t(msg.messageKey)}</AlertDescription>
|
||||
<AlertDescription>{t(msg.messageKey, msg.values)}</AlertDescription>
|
||||
</Alert>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -24,6 +24,8 @@ export type ConditionalMessage = {
|
||||
severity: MessageSeverity;
|
||||
/** Function returning true when the message should be shown */
|
||||
condition: (ctx: MessageConditionContext) => boolean;
|
||||
/** Optional interpolation values passed to t() for {{var}} substitution */
|
||||
values?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/** Field-level conditional message, adds field targeting */
|
||||
|
||||
@@ -175,6 +175,9 @@ export interface BaseSectionProps {
|
||||
isSavingAll?: boolean;
|
||||
/** Callback when this section's saving state changes */
|
||||
onSavingChange?: (isSaving: boolean) => void;
|
||||
/** When true, render the form fields only; suppress the internal save/undo bar.
|
||||
* The parent owns the save action and reads pending data via `onPendingDataChange`. */
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
export interface CreateSectionOptions {
|
||||
@@ -211,6 +214,7 @@ export function ConfigSection({
|
||||
onDeleteProfileSection,
|
||||
isSavingAll = false,
|
||||
onSavingChange,
|
||||
embedded = false,
|
||||
}: ConfigSectionProps) {
|
||||
// For replay level, treat as camera-level config access
|
||||
const effectiveLevel = level === "replay" ? "camera" : level;
|
||||
@@ -1048,121 +1052,123 @@ export function ConfigSection({
|
||||
}}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"w-full border-t border-secondary bg-background pt-0",
|
||||
!noStickyButtons && "sticky bottom-0 z-50",
|
||||
)}
|
||||
>
|
||||
{!embedded && (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-4 pt-2 md:flex-row",
|
||||
hasChanges ? "justify-between" : "justify-end",
|
||||
"w-full border-t border-secondary bg-background pt-0",
|
||||
!noStickyButtons && "sticky bottom-0 z-50",
|
||||
)}
|
||||
>
|
||||
{hasChanges && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-unsaved">
|
||||
{t("unsavedChanges", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "You have unsaved changes",
|
||||
})}
|
||||
</span>
|
||||
<SaveAllPreviewPopover
|
||||
items={sectionPreviewItems}
|
||||
className="h-7 w-7"
|
||||
align="start"
|
||||
side="top"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-full flex-col gap-2 sm:flex-row sm:items-center md:w-auto">
|
||||
{((effectiveLevel === "camera" && isOverridden) ||
|
||||
effectiveLevel === "global") &&
|
||||
!hasChanges &&
|
||||
!skipSave &&
|
||||
!profileName && (
|
||||
<Button
|
||||
onClick={() => setIsResetDialogOpen(true)}
|
||||
variant="outline"
|
||||
disabled={isSaving || isResettingToDefault || disabled}
|
||||
className="flex flex-1 gap-2"
|
||||
>
|
||||
{isResettingToDefault && (
|
||||
<ActivityIndicator className="h-4 w-4" />
|
||||
)}
|
||||
{effectiveLevel === "global"
|
||||
? t("button.resetToDefault", {
|
||||
ns: "common",
|
||||
defaultValue: "Reset to Default",
|
||||
})
|
||||
: t("button.resetToGlobal", {
|
||||
ns: "common",
|
||||
defaultValue: "Reset to Global",
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
{profileName &&
|
||||
profileOverridesSection &&
|
||||
!hasChanges &&
|
||||
!skipSave &&
|
||||
onDeleteProfileSection && (
|
||||
<Button
|
||||
onClick={() => setIsDeleteProfileDialogOpen(true)}
|
||||
variant="outline"
|
||||
disabled={isSaving || disabled}
|
||||
className="flex flex-1 gap-2"
|
||||
>
|
||||
{t("profiles.removeOverride", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Remove Profile Override",
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-4 pt-2 md:flex-row",
|
||||
hasChanges ? "justify-between" : "justify-end",
|
||||
)}
|
||||
>
|
||||
{hasChanges && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-unsaved">
|
||||
{t("unsavedChanges", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "You have unsaved changes",
|
||||
})}
|
||||
</span>
|
||||
<SaveAllPreviewPopover
|
||||
items={sectionPreviewItems}
|
||||
className="h-7 w-7"
|
||||
align="start"
|
||||
side="top"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-full flex-col gap-2 sm:flex-row sm:items-center md:w-auto">
|
||||
{((effectiveLevel === "camera" && isOverridden) ||
|
||||
effectiveLevel === "global") &&
|
||||
!hasChanges &&
|
||||
!skipSave &&
|
||||
!profileName && (
|
||||
<Button
|
||||
onClick={() => setIsResetDialogOpen(true)}
|
||||
variant="outline"
|
||||
disabled={isSaving || isResettingToDefault || disabled}
|
||||
className="flex flex-1 gap-2"
|
||||
>
|
||||
{isResettingToDefault && (
|
||||
<ActivityIndicator className="h-4 w-4" />
|
||||
)}
|
||||
{effectiveLevel === "global"
|
||||
? t("button.resetToDefault", {
|
||||
ns: "common",
|
||||
defaultValue: "Reset to Default",
|
||||
})
|
||||
: t("button.resetToGlobal", {
|
||||
ns: "common",
|
||||
defaultValue: "Reset to Global",
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
{profileName &&
|
||||
profileOverridesSection &&
|
||||
!hasChanges &&
|
||||
!skipSave &&
|
||||
onDeleteProfileSection && (
|
||||
<Button
|
||||
onClick={() => setIsDeleteProfileDialogOpen(true)}
|
||||
variant="outline"
|
||||
disabled={isSaving || disabled}
|
||||
className="flex flex-1 gap-2"
|
||||
>
|
||||
{t("profiles.removeOverride", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Remove Profile Override",
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
{hasChanges && (
|
||||
<Button
|
||||
onClick={handleReset}
|
||||
variant="outline"
|
||||
disabled={isSaving || isSavingAll || disabled}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{t("button.undo", { ns: "common", defaultValue: "Undo" })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={handleReset}
|
||||
variant="outline"
|
||||
disabled={isSaving || isSavingAll || disabled}
|
||||
onClick={handleSave}
|
||||
variant="select"
|
||||
disabled={
|
||||
!hasChanges ||
|
||||
hasValidationErrors ||
|
||||
isSaving ||
|
||||
isSavingAll ||
|
||||
disabled
|
||||
}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{t("button.undo", { ns: "common", defaultValue: "Undo" })}
|
||||
{isSaving ? (
|
||||
<>
|
||||
<ActivityIndicator className="h-4 w-4" />
|
||||
{skipSave
|
||||
? t("button.applying", {
|
||||
ns: "common",
|
||||
defaultValue: "Applying...",
|
||||
})
|
||||
: t("button.saving", {
|
||||
ns: "common",
|
||||
defaultValue: "Saving...",
|
||||
})}
|
||||
</>
|
||||
) : skipSave ? (
|
||||
t("button.apply", { ns: "common", defaultValue: "Apply" })
|
||||
) : (
|
||||
t("button.save", { ns: "common", defaultValue: "Save" })
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
variant="select"
|
||||
disabled={
|
||||
!hasChanges ||
|
||||
hasValidationErrors ||
|
||||
isSaving ||
|
||||
isSavingAll ||
|
||||
disabled
|
||||
}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<ActivityIndicator className="h-4 w-4" />
|
||||
{skipSave
|
||||
? t("button.applying", {
|
||||
ns: "common",
|
||||
defaultValue: "Applying...",
|
||||
})
|
||||
: t("button.saving", {
|
||||
ns: "common",
|
||||
defaultValue: "Saving...",
|
||||
})}
|
||||
</>
|
||||
) : skipSave ? (
|
||||
t("button.apply", { ns: "common", defaultValue: "Apply" })
|
||||
) : (
|
||||
t("button.save", { ns: "common", defaultValue: "Save" })
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AlertDialog open={isResetDialogOpen} onOpenChange={setIsResetDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
|
||||
@@ -44,7 +44,7 @@ import FrigatePlusSettingsView from "@/views/settings/FrigatePlusSettingsView";
|
||||
import MediaSyncSettingsView from "@/views/settings/MediaSyncSettingsView";
|
||||
import RegionGridSettingsView from "@/views/settings/RegionGridSettingsView";
|
||||
import Go2RtcStreamsSettingsView from "@/views/settings/Go2RtcStreamsSettingsView";
|
||||
import SystemDetectionModelSettingsView from "@/views/settings/SystemDetectionModelSettingsView";
|
||||
import DetectorsAndModelSettingsView from "@/views/settings/DetectorsAndModelSettingsView";
|
||||
import {
|
||||
SingleSectionPage,
|
||||
type SettingsPageProps,
|
||||
@@ -127,8 +127,7 @@ const allSettingsViews = [
|
||||
"systemEnvironmentVariables",
|
||||
"systemTelemetry",
|
||||
"systemBirdseye",
|
||||
"systemDetectorHardware",
|
||||
"systemDetectionModel",
|
||||
"systemDetectorsAndModel",
|
||||
"systemMqtt",
|
||||
"systemGo2rtcStreams",
|
||||
"integrationSemanticSearch",
|
||||
@@ -229,11 +228,6 @@ const SystemEnvironmentVariablesSettingsPage = createSectionPage(
|
||||
);
|
||||
const SystemTelemetrySettingsPage = createSectionPage("telemetry", "global");
|
||||
const SystemBirdseyeSettingsPage = createSectionPage("birdseye", "global");
|
||||
const SystemDetectorHardwareSettingsPage = createSectionPage(
|
||||
"detectors",
|
||||
"global",
|
||||
);
|
||||
const SystemDetectionModelSettingsPage = SystemDetectionModelSettingsView;
|
||||
const NotificationsSettingsPage = createSectionPage("notifications", "global");
|
||||
|
||||
const SystemMqttSettingsPage = createSectionPage("mqtt", "global");
|
||||
@@ -399,12 +393,8 @@ const settingsGroups = [
|
||||
component: Go2RtcStreamsSettingsView,
|
||||
},
|
||||
{
|
||||
key: "systemDetectorHardware",
|
||||
component: SystemDetectorHardwareSettingsPage,
|
||||
},
|
||||
{
|
||||
key: "systemDetectionModel",
|
||||
component: SystemDetectionModelSettingsPage,
|
||||
key: "systemDetectorsAndModel",
|
||||
component: DetectorsAndModelSettingsView,
|
||||
},
|
||||
{ key: "systemDatabase", component: SystemDatabaseSettingsPage },
|
||||
{ key: "systemMqtt", component: SystemMqttSettingsPage },
|
||||
@@ -558,8 +548,8 @@ const SYSTEM_SECTION_MAPPING: Record<string, SettingsType> = {
|
||||
environment_vars: "systemEnvironmentVariables",
|
||||
telemetry: "systemTelemetry",
|
||||
birdseye: "systemBirdseye",
|
||||
detectors: "systemDetectorHardware",
|
||||
model: "systemDetectionModel",
|
||||
detectors: "systemDetectorsAndModel",
|
||||
model: "systemDetectorsAndModel",
|
||||
};
|
||||
|
||||
const CAMERA_SECTION_KEYS = new Set<SettingsType>(
|
||||
|
||||
@@ -0,0 +1,797 @@
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import { LuExternalLink, LuFilter } from "react-icons/lu";
|
||||
import { toast } from "sonner";
|
||||
import axios from "axios";
|
||||
import useSWR from "swr";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useRestart } from "@/api/ws";
|
||||
import RestartDialog from "@/components/overlay/dialog/RestartDialog";
|
||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||
import { StatusBarMessagesContext } from "@/context/statusbar-provider";
|
||||
import ActivityIndicator from "@/components/indicators/activity-indicator";
|
||||
import Heading from "@/components/ui/heading";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
} from "@/components/ui/select";
|
||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||
import type {
|
||||
SectionStatus,
|
||||
SettingsPageProps,
|
||||
} from "@/views/settings/SingleSectionPage";
|
||||
import type { ConfigSectionData } from "@/types/configForm";
|
||||
import {
|
||||
SettingsGroupCard,
|
||||
SplitCardRow,
|
||||
} from "@/components/card/SettingsGroupCard";
|
||||
import { ConfigSectionTemplate } from "@/components/config-form/sections";
|
||||
import { ConfigMessageBanner } from "@/components/config-form/ConfigMessageBanner";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
|
||||
type ModelTab = "plus" | "custom";
|
||||
|
||||
type PageState = {
|
||||
detectors: ConfigSectionData;
|
||||
modelTab: ModelTab;
|
||||
plusModelId: string | undefined;
|
||||
customModel: ConfigSectionData;
|
||||
};
|
||||
|
||||
type FrigatePlusModel = {
|
||||
id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
isBaseModel: boolean;
|
||||
supportedDetectors: string[];
|
||||
trainDate: string;
|
||||
baseModel: string;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
const TYPE_MODEL_DEFAULTS: Record<string, ConfigSectionData> = {
|
||||
cpu: {
|
||||
path: "/cpu_model.tflite",
|
||||
labelmap_path: "/labelmap.txt",
|
||||
width: 320,
|
||||
height: 320,
|
||||
input_tensor: "nhwc",
|
||||
input_pixel_format: "rgb",
|
||||
input_dtype: "int",
|
||||
model_type: "ssd",
|
||||
},
|
||||
edgetpu: {
|
||||
path: "/edgetpu_model.tflite",
|
||||
labelmap_path: "/labelmap.txt",
|
||||
width: 320,
|
||||
height: 320,
|
||||
input_tensor: "nhwc",
|
||||
input_pixel_format: "rgb",
|
||||
input_dtype: "int",
|
||||
model_type: "ssd",
|
||||
},
|
||||
openvino: {
|
||||
path: "/openvino-model/ssdlite_mobilenet_v2.xml",
|
||||
labelmap_path: "/openvino-model/coco_91cl_bkgr.txt",
|
||||
width: 300,
|
||||
height: 300,
|
||||
input_tensor: "nhwc",
|
||||
input_pixel_format: "bgr",
|
||||
input_dtype: "int",
|
||||
model_type: "ssd",
|
||||
},
|
||||
};
|
||||
|
||||
const STATUS_BAR_KEY = "detectors_and_model";
|
||||
|
||||
const deriveInitialState = (config: FrigateConfig): PageState => {
|
||||
const plusModelId = config.model?.plus?.id;
|
||||
const modelPath = config.model?.path;
|
||||
const plusEnabled = Boolean(config.plus?.enabled);
|
||||
|
||||
// The reliable signal that a Plus model is currently active is the
|
||||
// `model.plus.id` metadata
|
||||
let modelTab: ModelTab;
|
||||
if (plusModelId) {
|
||||
modelTab = "plus";
|
||||
} else if (typeof modelPath === "string" && modelPath.length > 0) {
|
||||
modelTab = "custom";
|
||||
} else if (plusEnabled) {
|
||||
modelTab = "plus";
|
||||
} else {
|
||||
modelTab = "custom";
|
||||
}
|
||||
// Fallback: if Plus is not enabled, prefer Custom regardless of saved state
|
||||
if (!plusEnabled && modelTab === "plus") {
|
||||
modelTab = "custom";
|
||||
}
|
||||
|
||||
const { plus: _plus, ...modelWithoutPlus } = (config.model ?? {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
// If a Plus model is active, the resolved `model.path` is auto-derived from
|
||||
// `plus.id` — drop it so the Custom tab starts clean and doesn't silently
|
||||
// re-save the same Plus model when the user thinks they switched modes.
|
||||
if (plusModelId) {
|
||||
delete modelWithoutPlus.path;
|
||||
}
|
||||
|
||||
return {
|
||||
detectors: (config.detectors ?? {}) as ConfigSectionData,
|
||||
modelTab,
|
||||
plusModelId: plusModelId ?? undefined,
|
||||
customModel: modelWithoutPlus as ConfigSectionData,
|
||||
};
|
||||
};
|
||||
|
||||
export default function DetectorsAndModelSettingsView({
|
||||
setUnsavedChanges,
|
||||
}: SettingsPageProps) {
|
||||
const { t } = useTranslation(["views/settings", "common"]);
|
||||
const { getLocaleDocUrl } = useDocDomain();
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const { mutate: globalMutate } = useSWRConfig();
|
||||
const { addMessage, removeMessage } = useContext(StatusBarMessagesContext)!;
|
||||
|
||||
const [snapshot, setSnapshot] = useState<PageState | null>(null);
|
||||
const [state, setState] = useState<PageState | null>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
const [restartDialogOpen, setRestartDialogOpen] = useState(false);
|
||||
const { send: sendRestart } = useRestart();
|
||||
const [childPending, setChildPending] = useState<
|
||||
Record<string, ConfigSectionData>
|
||||
>({});
|
||||
const [detectorStatus, setDetectorStatus] = useState<SectionStatus>({
|
||||
hasChanges: false,
|
||||
isOverridden: false,
|
||||
hasValidationErrors: false,
|
||||
});
|
||||
const [modelStatus, setModelStatus] = useState<SectionStatus>({
|
||||
hasChanges: false,
|
||||
isOverridden: false,
|
||||
hasValidationErrors: false,
|
||||
});
|
||||
|
||||
const [showBaseModels, setShowBaseModels] = useState(true);
|
||||
const [showFineTunedModels, setShowFineTunedModels] = useState(true);
|
||||
|
||||
const plusEnabled = Boolean(config?.plus?.enabled);
|
||||
|
||||
const { data: availableModels = {}, isLoading: isLoadingModels } = useSWR<
|
||||
Record<string, FrigatePlusModel>
|
||||
>(plusEnabled ? "/plus/models" : null, {
|
||||
fallbackData: {},
|
||||
fetcher: async (url) => {
|
||||
const res = await axios.get(url, { withCredentials: true });
|
||||
return res.data.reduce(
|
||||
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
|
||||
obj[model.id] = model;
|
||||
return obj;
|
||||
},
|
||||
{},
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const filteredModelEntries = useMemo(
|
||||
() =>
|
||||
Object.entries(availableModels || {}).filter(([, model]) =>
|
||||
model.isBaseModel ? showBaseModels : showFineTunedModels,
|
||||
),
|
||||
[availableModels, showBaseModels, showFineTunedModels],
|
||||
);
|
||||
|
||||
const isFilterActive = !showBaseModels || !showFineTunedModels;
|
||||
|
||||
const currentDetectorType = useMemo(() => {
|
||||
if (!state) return undefined;
|
||||
const values = Object.values(state.detectors ?? {});
|
||||
if (values.length === 0) return undefined;
|
||||
const first = values[0] as { type?: string } | undefined;
|
||||
return first?.type;
|
||||
}, [state]);
|
||||
|
||||
// fill in defaults when detector type changes
|
||||
const prevDetectorTypeRef = useRef<string | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
const newType = currentDetectorType;
|
||||
const prevType = prevDetectorTypeRef.current;
|
||||
prevDetectorTypeRef.current = newType;
|
||||
if (prevType === undefined || prevType === newType) return;
|
||||
if (!newType || !(newType in TYPE_MODEL_DEFAULTS)) return;
|
||||
|
||||
const defaults = TYPE_MODEL_DEFAULTS[newType];
|
||||
setChildPending((prev) => {
|
||||
const next: Record<string, ConfigSectionData> = {
|
||||
...prev,
|
||||
model: defaults,
|
||||
};
|
||||
if (newType === "openvino") {
|
||||
const detectorsCurrent = (prev.detectors ?? state?.detectors ?? {}) as {
|
||||
[key: string]: { device?: string };
|
||||
};
|
||||
const entries = Object.entries(detectorsCurrent);
|
||||
if (entries.length > 0) {
|
||||
const [firstKey, firstValue] = entries[0];
|
||||
if (!firstValue?.device) {
|
||||
next.detectors = {
|
||||
...detectorsCurrent,
|
||||
[firstKey]: { ...firstValue, device: "CPU" },
|
||||
} as ConfigSectionData;
|
||||
}
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentDetectorType]);
|
||||
|
||||
const isModelCompatible = useCallback(
|
||||
(model: FrigatePlusModel) =>
|
||||
currentDetectorType
|
||||
? model.supportedDetectors.includes(currentDetectorType)
|
||||
: true,
|
||||
[currentDetectorType],
|
||||
);
|
||||
|
||||
const selectedPlusModel = state?.plusModelId
|
||||
? availableModels?.[state.plusModelId]
|
||||
: undefined;
|
||||
|
||||
const plusMismatch =
|
||||
state?.modelTab === "plus" &&
|
||||
selectedPlusModel !== undefined &&
|
||||
currentDetectorType !== undefined &&
|
||||
!isModelCompatible(selectedPlusModel);
|
||||
|
||||
const plusModelMissing = state?.modelTab === "plus" && !state?.plusModelId;
|
||||
|
||||
const handleChildPendingChange = useCallback(
|
||||
(
|
||||
sectionKey: string,
|
||||
_cameraName: string | undefined,
|
||||
data: ConfigSectionData | null,
|
||||
) => {
|
||||
setChildPending((prev) => {
|
||||
if (data === null) {
|
||||
if (!(sectionKey in prev)) return prev;
|
||||
const { [sectionKey]: _drop, ...rest } = prev;
|
||||
return rest;
|
||||
}
|
||||
return { ...prev, [sectionKey]: data };
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleDetectorStatusChange = useCallback(
|
||||
(status: SectionStatus) => setDetectorStatus(status),
|
||||
[],
|
||||
);
|
||||
|
||||
const handleModelStatusChange = useCallback(
|
||||
(status: SectionStatus) => setModelStatus(status),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const detectorsPending = childPending["detectors"];
|
||||
setState((prev) => {
|
||||
if (!prev || !snapshot) return prev;
|
||||
// When the embedded form un-modifies (data returns to baseline) it clears
|
||||
// its entry from childPending — fall back to snapshot so state.detectors
|
||||
// doesn't keep a stale value the user has visually reverted.
|
||||
return {
|
||||
...prev,
|
||||
detectors: detectorsPending ?? snapshot.detectors,
|
||||
};
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [childPending["detectors"]]);
|
||||
|
||||
useEffect(() => {
|
||||
const modelPending = childPending["model"];
|
||||
setState((prev) => {
|
||||
if (!prev || !snapshot) return prev;
|
||||
return {
|
||||
...prev,
|
||||
customModel: modelPending ?? snapshot.customModel,
|
||||
};
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [childPending["model"]]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!config || snapshot !== null) return;
|
||||
const initial = deriveInitialState(config);
|
||||
setSnapshot(initial);
|
||||
setState(initial);
|
||||
}, [config, snapshot]);
|
||||
|
||||
const isDirty = useMemo(() => {
|
||||
if (!state || !snapshot) return false;
|
||||
return JSON.stringify(state) !== JSON.stringify(snapshot);
|
||||
}, [state, snapshot]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isDirty) {
|
||||
addMessage(
|
||||
STATUS_BAR_KEY,
|
||||
t("detectorsAndModel.unsavedChanges"),
|
||||
undefined,
|
||||
STATUS_BAR_KEY,
|
||||
);
|
||||
} else {
|
||||
removeMessage(STATUS_BAR_KEY, STATUS_BAR_KEY);
|
||||
}
|
||||
setUnsavedChanges?.(isDirty);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isDirty]);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = t("documentTitle.detectorsAndModel");
|
||||
}, [t]);
|
||||
|
||||
const onSave = useCallback(async () => {
|
||||
if (!state || !snapshot) return;
|
||||
|
||||
const tabChanged = state.modelTab !== snapshot.modelTab;
|
||||
|
||||
const modelPayload =
|
||||
state.modelTab === "plus"
|
||||
? { path: `plus://${state.plusModelId}` }
|
||||
: state.customModel;
|
||||
|
||||
const detectorKeysChanged =
|
||||
JSON.stringify(Object.keys(state.detectors).sort()) !==
|
||||
JSON.stringify(Object.keys(snapshot.detectors).sort());
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
if (tabChanged) {
|
||||
// Best-effort cleanup of the prior model's fields
|
||||
try {
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: { model: null },
|
||||
});
|
||||
} catch {
|
||||
// intentional no-op — see comment above
|
||||
}
|
||||
}
|
||||
|
||||
if (detectorKeysChanged) {
|
||||
// Best-effort cleanup
|
||||
try {
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: { detectors: null },
|
||||
});
|
||||
} catch {
|
||||
// intentional no-op — see comment above
|
||||
}
|
||||
}
|
||||
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: {
|
||||
detectors: state.detectors,
|
||||
model: modelPayload,
|
||||
},
|
||||
});
|
||||
|
||||
await globalMutate("config");
|
||||
await globalMutate("config/raw_paths");
|
||||
|
||||
// Re-derive snapshot from the freshly saved state so isDirty resets.
|
||||
setSnapshot({ ...state });
|
||||
setChildPending({});
|
||||
setResetKey((k) => k + 1);
|
||||
|
||||
addMessage(
|
||||
"detectors_and_model_restart",
|
||||
t("detectorsAndModel.restartRequired"),
|
||||
undefined,
|
||||
"detectors_and_model_restart",
|
||||
);
|
||||
|
||||
toast.success(t("detectorsAndModel.toast.saveSuccess"), {
|
||||
position: "top-center",
|
||||
action: (
|
||||
<Button onClick={() => setRestartDialogOpen(true)}>
|
||||
{t("restart.button", { ns: "components/dialog" })}
|
||||
</Button>
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
const err = error as {
|
||||
response?: { data?: { message?: string; detail?: string } };
|
||||
};
|
||||
const message =
|
||||
err.response?.data?.message ||
|
||||
err.response?.data?.detail ||
|
||||
t("detectorsAndModel.toast.saveError");
|
||||
toast.error(message, { position: "top-center" });
|
||||
// Re-sync the config cache in case the two-step PUT left the backend
|
||||
// ahead of the frontend (e.g. step 1 cleared `model` but step 2 failed).
|
||||
await globalMutate("config");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}, [state, snapshot, globalMutate, addMessage, t]);
|
||||
|
||||
const onUndo = useCallback(() => {
|
||||
if (snapshot) {
|
||||
setState(snapshot);
|
||||
setChildPending({});
|
||||
// Force the embedded forms to re-mount so their internal dirty/baseline
|
||||
// state is rebuilt from the current config — clearing childPending alone
|
||||
// doesn't reset BaseSection's internal tracking.
|
||||
setResetKey((k) => k + 1);
|
||||
}
|
||||
}, [snapshot]);
|
||||
|
||||
if (!config || !state) {
|
||||
return <ActivityIndicator />;
|
||||
}
|
||||
|
||||
const saveDisabled =
|
||||
!isDirty ||
|
||||
isSaving ||
|
||||
detectorStatus.hasValidationErrors ||
|
||||
(state.modelTab === "custom" && modelStatus.hasValidationErrors) ||
|
||||
plusMismatch ||
|
||||
plusModelMissing;
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col md:pr-2">
|
||||
<Toaster position="top-center" closeButton={true} />
|
||||
<div className="mb-1 flex items-center justify-between gap-4 pt-2">
|
||||
<div className="flex max-w-5xl flex-col">
|
||||
<Heading as="h4">{t("detectorsAndModel.title")}</Heading>
|
||||
<div className="my-1 text-sm text-muted-foreground">
|
||||
{t("detectorsAndModel.description")}
|
||||
</div>
|
||||
<div className="flex items-center text-sm text-primary-variant">
|
||||
<Link
|
||||
to={getLocaleDocUrl("/configuration/object_detectors")}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline"
|
||||
>
|
||||
{t("readTheDocumentation", { ns: "common" })}
|
||||
<LuExternalLink className="ml-2 inline-flex size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
{isDirty && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-default bg-unsaved text-xs text-black hover:bg-unsaved"
|
||||
>
|
||||
{t("button.modified", { ns: "common", defaultValue: "Modified" })}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-full max-w-5xl space-y-6 pt-4">
|
||||
<div className="space-y-6">
|
||||
<SettingsGroupCard title={t("detectorsAndModel.cardTitles.detector")}>
|
||||
<ConfigSectionTemplate
|
||||
key={`detectors-${resetKey}`}
|
||||
sectionKey="detectors"
|
||||
level="global"
|
||||
showOverrideIndicator={false}
|
||||
showTitle={false}
|
||||
embedded
|
||||
pendingDataBySection={childPending}
|
||||
onPendingDataChange={handleChildPendingChange}
|
||||
onStatusChange={handleDetectorStatusChange}
|
||||
/>
|
||||
</SettingsGroupCard>
|
||||
{plusMismatch && selectedPlusModel && (
|
||||
<ConfigMessageBanner
|
||||
messages={[
|
||||
{
|
||||
key: "plus-mismatch",
|
||||
messageKey: "detectorsAndModel.mismatch.warning",
|
||||
severity: "warning",
|
||||
condition: () => true,
|
||||
values: {
|
||||
model: selectedPlusModel.name,
|
||||
required: selectedPlusModel.supportedDetectors.join(", "),
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<SettingsGroupCard title={t("detectorsAndModel.cardTitles.model")}>
|
||||
{plusEnabled ? (
|
||||
<Tabs
|
||||
value={state.modelTab}
|
||||
onValueChange={(value) =>
|
||||
setState((prev) =>
|
||||
prev ? { ...prev, modelTab: value as ModelTab } : prev,
|
||||
)
|
||||
}
|
||||
>
|
||||
<TabsList className="mb-4">
|
||||
<TabsTrigger value="plus">
|
||||
{t("detectorsAndModel.tabs.plus")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="custom">
|
||||
{t("detectorsAndModel.tabs.custom")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="plus">
|
||||
<SplitCardRow
|
||||
label={t("frigatePlus.modelInfo.availableModels")}
|
||||
description={
|
||||
<Trans ns="views/settings">
|
||||
frigatePlus.modelInfo.modelSelect
|
||||
</Trans>
|
||||
}
|
||||
content={
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Select
|
||||
value={state.plusModelId}
|
||||
onValueChange={(value) =>
|
||||
setState((prev) =>
|
||||
prev ? { ...prev, plusModelId: value } : prev,
|
||||
)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
{state.plusModelId &&
|
||||
availableModels?.[state.plusModelId]
|
||||
? new Date(
|
||||
availableModels[state.plusModelId].trainDate,
|
||||
).toLocaleString() +
|
||||
" " +
|
||||
availableModels[state.plusModelId].baseModel +
|
||||
" (" +
|
||||
(availableModels[state.plusModelId].isBaseModel
|
||||
? t(
|
||||
"frigatePlus.modelInfo.plusModelType.baseModel",
|
||||
)
|
||||
: t(
|
||||
"frigatePlus.modelInfo.plusModelType.userModel",
|
||||
)) +
|
||||
") " +
|
||||
availableModels[state.plusModelId].name +
|
||||
" (" +
|
||||
availableModels[state.plusModelId].width +
|
||||
"x" +
|
||||
availableModels[state.plusModelId].height +
|
||||
")"
|
||||
: isLoadingModels
|
||||
? t(
|
||||
"frigatePlus.modelInfo.loadingAvailableModels",
|
||||
)
|
||||
: t(
|
||||
"detectorsAndModel.plusModel.noModelSelected",
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{filteredModelEntries.length === 0 ? (
|
||||
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
||||
{t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||
</div>
|
||||
) : (
|
||||
filteredModelEntries.map(([id, model]) => (
|
||||
<SelectItem
|
||||
key={id}
|
||||
className="cursor-pointer"
|
||||
value={id}
|
||||
disabled={!isModelCompatible(model)}
|
||||
>
|
||||
{new Date(model.trainDate).toLocaleString()}{" "}
|
||||
<div>
|
||||
{model.baseModel} {" ("}
|
||||
{model.isBaseModel
|
||||
? t(
|
||||
"frigatePlus.modelInfo.plusModelType.baseModel",
|
||||
)
|
||||
: t(
|
||||
"frigatePlus.modelInfo.plusModelType.userModel",
|
||||
)}
|
||||
{")"}
|
||||
</div>
|
||||
<div>
|
||||
{model.name} (
|
||||
{model.width + "x" + model.height})
|
||||
</div>
|
||||
<div>
|
||||
{t(
|
||||
"frigatePlus.modelInfo.supportedDetectors",
|
||||
)}
|
||||
: {model.supportedDetectors.join(", ")}
|
||||
</div>
|
||||
{!isModelCompatible(model) && (
|
||||
<div className="text-xs text-danger">
|
||||
{t(
|
||||
"detectorsAndModel.plusModel.requiresDetector",
|
||||
{
|
||||
detector:
|
||||
model.supportedDetectors.join(
|
||||
", ",
|
||||
),
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{id}
|
||||
</div>
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="focus:outline-none"
|
||||
aria-label={t(
|
||||
"frigatePlus.modelInfo.filter.ariaLabel",
|
||||
)}
|
||||
>
|
||||
<LuFilter
|
||||
className={cn(
|
||||
"size-4",
|
||||
isFilterActive
|
||||
? "text-selected"
|
||||
: "text-secondary-foreground",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-56">
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm text-primary-variant">
|
||||
{t("frigatePlus.modelInfo.filter.ariaLabel")}
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="filterBaseModels"
|
||||
className="cursor-pointer text-primary"
|
||||
>
|
||||
{t("frigatePlus.modelInfo.filter.baseModels")}
|
||||
</Label>
|
||||
<Switch
|
||||
id="filterBaseModels"
|
||||
checked={showBaseModels}
|
||||
onCheckedChange={setShowBaseModels}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="filterFineTunedModels"
|
||||
className="cursor-pointer text-primary"
|
||||
>
|
||||
{t(
|
||||
"frigatePlus.modelInfo.filter.fineTunedModels",
|
||||
)}
|
||||
</Label>
|
||||
<Switch
|
||||
id="filterFineTunedModels"
|
||||
checked={showFineTunedModels}
|
||||
onCheckedChange={setShowFineTunedModels}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="custom">
|
||||
<ConfigSectionTemplate
|
||||
key={`model-${resetKey}`}
|
||||
sectionKey="model"
|
||||
level="global"
|
||||
showOverrideIndicator={false}
|
||||
showTitle={false}
|
||||
embedded
|
||||
pendingDataBySection={childPending}
|
||||
onPendingDataChange={handleChildPendingChange}
|
||||
onStatusChange={handleModelStatusChange}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
) : (
|
||||
<ConfigSectionTemplate
|
||||
key={`model-${resetKey}`}
|
||||
sectionKey="model"
|
||||
level="global"
|
||||
showOverrideIndicator={false}
|
||||
showTitle={false}
|
||||
embedded
|
||||
pendingDataBySection={childPending}
|
||||
onPendingDataChange={handleChildPendingChange}
|
||||
onStatusChange={handleModelStatusChange}
|
||||
/>
|
||||
)}
|
||||
</SettingsGroupCard>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sticky bottom-0 z-50 mt-6 w-full border-t border-secondary bg-background pt-0">
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-4 pt-2 md:flex-row",
|
||||
isDirty ? "justify-between" : "justify-end",
|
||||
)}
|
||||
>
|
||||
{isDirty && (
|
||||
<span className="text-sm text-unsaved">
|
||||
{t("unsavedChanges", { ns: "views/settings" })}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex w-full flex-col gap-2 sm:flex-row sm:items-center md:w-auto">
|
||||
{isDirty && (
|
||||
<Button
|
||||
onClick={onUndo}
|
||||
variant="outline"
|
||||
disabled={isSaving}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{t("button.undo", { ns: "common" })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={onSave}
|
||||
variant="select"
|
||||
disabled={saveDisabled}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<ActivityIndicator className="h-4 w-4" />
|
||||
{t("button.saving", { ns: "common" })}
|
||||
</>
|
||||
) : (
|
||||
t("button.save", { ns: "common" })
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<RestartDialog
|
||||
isOpen={restartDialogOpen}
|
||||
onClose={() => setRestartDialogOpen(false)}
|
||||
onRestart={() => sendRestart("restart")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,234 +1,28 @@
|
||||
import Heading from "@/components/ui/heading";
|
||||
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import useSWR from "swr";
|
||||
import { CheckCircle2, XCircle } from "lucide-react";
|
||||
import { LuExternalLink } from "react-icons/lu";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import ActivityIndicator from "@/components/indicators/activity-indicator";
|
||||
import { toast } from "sonner";
|
||||
import useSWR from "swr";
|
||||
import axios from "axios";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
import { CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Link } from "react-router-dom";
|
||||
import { LuExternalLink, LuFilter } from "react-icons/lu";
|
||||
import { StatusBarMessagesContext } from "@/context/statusbar-provider";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
||||
import Heading from "@/components/ui/heading";
|
||||
import {
|
||||
SettingsGroupCard,
|
||||
SplitCardRow,
|
||||
} from "@/components/card/SettingsGroupCard";
|
||||
import FrigatePlusCurrentModelSummary from "@/views/settings/components/FrigatePlusCurrentModelSummary";
|
||||
import { useRestart } from "@/api/ws";
|
||||
import RestartDialog from "@/components/overlay/dialog/RestartDialog";
|
||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
|
||||
|
||||
type FrigatePlusModel = {
|
||||
id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
isBaseModel: boolean;
|
||||
supportedDetectors: string[];
|
||||
trainDate: string;
|
||||
baseModel: string;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
type FrigatePlusSettings = {
|
||||
model: {
|
||||
id?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type FrigateSettingsViewProps = {
|
||||
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
};
|
||||
|
||||
export default function FrigatePlusSettingsView({
|
||||
setUnsavedChanges,
|
||||
}: FrigateSettingsViewProps) {
|
||||
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
const { t } = useTranslation("views/settings");
|
||||
const { getLocaleDocUrl } = useDocDomain();
|
||||
const { data: config, mutate: updateConfig } =
|
||||
useSWR<FrigateConfig>("config");
|
||||
const [changedValue, setChangedValue] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [restartDialogOpen, setRestartDialogOpen] = useState(false);
|
||||
const { send: sendRestart } = useRestart();
|
||||
|
||||
const { addMessage, removeMessage } = useContext(StatusBarMessagesContext)!;
|
||||
|
||||
const [frigatePlusSettings, setFrigatePlusSettings] =
|
||||
useState<FrigatePlusSettings>({
|
||||
model: {
|
||||
id: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
const [origPlusSettings, setOrigPlusSettings] = useState<FrigatePlusSettings>(
|
||||
{
|
||||
model: {
|
||||
id: undefined,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const { data: availableModels = {}, isLoading: isLoadingModels } = useSWR<
|
||||
Record<string, FrigatePlusModel>
|
||||
>("/plus/models", {
|
||||
fallbackData: {},
|
||||
fetcher: async (url) => {
|
||||
const res = await axios.get(url, { withCredentials: true });
|
||||
return res.data.reduce(
|
||||
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
|
||||
obj[model.id] = model;
|
||||
return obj;
|
||||
},
|
||||
{},
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const [showBaseModels, setShowBaseModels] = useState(true);
|
||||
const [showFineTunedModels, setShowFineTunedModels] = useState(true);
|
||||
|
||||
const filteredModelEntries = useMemo(
|
||||
() =>
|
||||
Object.entries(availableModels || {}).filter(([, model]) =>
|
||||
model.isBaseModel ? showBaseModels : showFineTunedModels,
|
||||
),
|
||||
[availableModels, showBaseModels, showFineTunedModels],
|
||||
);
|
||||
|
||||
const isFilterActive = !showBaseModels || !showFineTunedModels;
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
if (frigatePlusSettings?.model.id == undefined) {
|
||||
setFrigatePlusSettings({
|
||||
model: {
|
||||
id: config.model.plus?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setOrigPlusSettings({
|
||||
model: {
|
||||
id: config.model.plus?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
// we know that these deps are correct
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [config]);
|
||||
|
||||
const handleFrigatePlusConfigChange = (
|
||||
newConfig: Partial<FrigatePlusSettings>,
|
||||
) => {
|
||||
setFrigatePlusSettings((prevConfig) => ({
|
||||
model: {
|
||||
...prevConfig.model,
|
||||
...newConfig.model,
|
||||
},
|
||||
}));
|
||||
setUnsavedChanges(true);
|
||||
setChangedValue(true);
|
||||
};
|
||||
|
||||
const saveToConfig = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Clear the existing model section so only the new path remains
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: { model: null },
|
||||
});
|
||||
const res = await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: {
|
||||
model: { path: `plus://${frigatePlusSettings.model.id}` },
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status === 200) {
|
||||
toast.success(t("frigatePlus.toast.success"), {
|
||||
position: "top-center",
|
||||
action: (
|
||||
<a onClick={() => setRestartDialogOpen(true)}>
|
||||
<Button>
|
||||
{t("restart.button", { ns: "components/dialog" })}
|
||||
</Button>
|
||||
</a>
|
||||
),
|
||||
});
|
||||
setChangedValue(false);
|
||||
updateConfig();
|
||||
} else {
|
||||
toast.error(
|
||||
t("frigatePlus.toast.error", { errorMessage: res.statusText }),
|
||||
{
|
||||
position: "top-center",
|
||||
},
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const err = error as {
|
||||
response?: { data?: { message?: string; detail?: string } };
|
||||
};
|
||||
const errorMessage =
|
||||
err.response?.data?.message ||
|
||||
err.response?.data?.detail ||
|
||||
"Unknown error";
|
||||
toast.error(t("toast.save.error.title", { errorMessage, ns: "common" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
} finally {
|
||||
addMessage(
|
||||
"plus_restart",
|
||||
t("frigatePlus.restart_required"),
|
||||
undefined,
|
||||
"plus_restart",
|
||||
);
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [updateConfig, addMessage, frigatePlusSettings, t]);
|
||||
|
||||
const onCancel = useCallback(() => {
|
||||
setFrigatePlusSettings(origPlusSettings);
|
||||
setChangedValue(false);
|
||||
removeMessage("plus_settings", "plus_settings");
|
||||
}, [origPlusSettings, removeMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (changedValue) {
|
||||
addMessage(
|
||||
"plus_settings",
|
||||
t("frigatePlus.unsavedChanges"),
|
||||
undefined,
|
||||
"plus_settings",
|
||||
);
|
||||
} else {
|
||||
removeMessage("plus_settings", "plus_settings");
|
||||
}
|
||||
// we know that these deps are correct
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [changedValue]);
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
document.title = t("documentTitle.frigatePlus");
|
||||
@@ -246,7 +40,6 @@ export default function FrigatePlusSettingsView({
|
||||
<Heading as="h4" className="mb-2">
|
||||
{t("frigatePlus.title")}
|
||||
</Heading>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("frigatePlus.description")}
|
||||
</p>
|
||||
@@ -292,170 +85,20 @@ export default function FrigatePlusSettingsView({
|
||||
</SettingsGroupCard>
|
||||
|
||||
{config?.plus?.enabled && (
|
||||
<FrigatePlusCurrentModelSummary plusModel={config.model.plus} />
|
||||
)}
|
||||
|
||||
{config?.plus?.enabled && (
|
||||
<SettingsGroupCard title={t("frigatePlus.cardTitles.otherModels")}>
|
||||
<SplitCardRow
|
||||
label={t("frigatePlus.modelInfo.availableModels")}
|
||||
description={
|
||||
<Trans ns="views/settings">
|
||||
frigatePlus.modelInfo.modelSelect
|
||||
</Trans>
|
||||
}
|
||||
content={
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Select
|
||||
value={frigatePlusSettings.model.id}
|
||||
onValueChange={(value) =>
|
||||
handleFrigatePlusConfigChange({
|
||||
model: { id: value as string },
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
{frigatePlusSettings.model.id &&
|
||||
availableModels?.[frigatePlusSettings.model.id]
|
||||
? new Date(
|
||||
availableModels[
|
||||
frigatePlusSettings.model.id
|
||||
].trainDate,
|
||||
).toLocaleString() +
|
||||
" " +
|
||||
availableModels[frigatePlusSettings.model.id]
|
||||
.baseModel +
|
||||
" (" +
|
||||
(availableModels[frigatePlusSettings.model.id]
|
||||
.isBaseModel
|
||||
? t(
|
||||
"frigatePlus.modelInfo.plusModelType.baseModel",
|
||||
)
|
||||
: t(
|
||||
"frigatePlus.modelInfo.plusModelType.userModel",
|
||||
)) +
|
||||
") " +
|
||||
availableModels[frigatePlusSettings.model.id].name +
|
||||
" (" +
|
||||
availableModels[frigatePlusSettings.model.id]
|
||||
.width +
|
||||
"x" +
|
||||
availableModels[frigatePlusSettings.model.id]
|
||||
.height +
|
||||
")"
|
||||
: isLoadingModels
|
||||
? t("frigatePlus.modelInfo.loadingAvailableModels")
|
||||
: t("frigatePlus.modelInfo.selectModel")}
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{filteredModelEntries.length === 0 ? (
|
||||
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
||||
{t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||
</div>
|
||||
) : (
|
||||
filteredModelEntries.map(([id, model]) => (
|
||||
<SelectItem
|
||||
key={id}
|
||||
className="cursor-pointer"
|
||||
value={id}
|
||||
disabled={
|
||||
!model.supportedDetectors.includes(
|
||||
Object.values(config.detectors)[0].type,
|
||||
)
|
||||
}
|
||||
>
|
||||
{new Date(model.trainDate).toLocaleString()}{" "}
|
||||
<div>
|
||||
{model.baseModel} {" ("}
|
||||
{model.isBaseModel
|
||||
? t(
|
||||
"frigatePlus.modelInfo.plusModelType.baseModel",
|
||||
)
|
||||
: t(
|
||||
"frigatePlus.modelInfo.plusModelType.userModel",
|
||||
)}
|
||||
{")"}
|
||||
</div>
|
||||
<div>
|
||||
{model.name} (
|
||||
{model.width + "x" + model.height})
|
||||
</div>
|
||||
<div>
|
||||
{t(
|
||||
"frigatePlus.modelInfo.supportedDetectors",
|
||||
)}
|
||||
: {model.supportedDetectors.join(", ")}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{id}
|
||||
</div>
|
||||
</SelectItem>
|
||||
))
|
||||
)}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="focus:outline-none"
|
||||
aria-label={t(
|
||||
"frigatePlus.modelInfo.filter.ariaLabel",
|
||||
)}
|
||||
>
|
||||
<LuFilter
|
||||
className={cn(
|
||||
"size-4",
|
||||
isFilterActive
|
||||
? "text-selected"
|
||||
: "text-secondary-foreground",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-56">
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm text-primary-variant">
|
||||
{t("frigatePlus.modelInfo.filter.ariaLabel")}
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="filterBaseModels"
|
||||
className="cursor-pointer text-primary"
|
||||
>
|
||||
{t("frigatePlus.modelInfo.filter.baseModels")}
|
||||
</Label>
|
||||
<Switch
|
||||
id="filterBaseModels"
|
||||
checked={showBaseModels}
|
||||
onCheckedChange={setShowBaseModels}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="filterFineTunedModels"
|
||||
className="cursor-pointer text-primary"
|
||||
>
|
||||
{t(
|
||||
"frigatePlus.modelInfo.filter.fineTunedModels",
|
||||
)}
|
||||
</Label>
|
||||
<Switch
|
||||
id="filterFineTunedModels"
|
||||
checked={showFineTunedModels}
|
||||
onCheckedChange={setShowFineTunedModels}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SettingsGroupCard>
|
||||
<FrigatePlusCurrentModelSummary
|
||||
plusModel={config.model.plus}
|
||||
action={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
navigate("/settings?page=systemDetectorsAndModel")
|
||||
}
|
||||
>
|
||||
{t("frigatePlus.changeInDetectorsAndModel")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
<SettingsGroupCard title={t("frigatePlus.cardTitles.configuration")}>
|
||||
@@ -524,55 +167,6 @@ export default function FrigatePlusSettingsView({
|
||||
</SettingsGroupCard>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sticky bottom-0 z-50 mt-6 w-full border-t border-secondary bg-background pt-0">
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-4 pt-2 md:flex-row",
|
||||
changedValue ? "justify-between" : "justify-end",
|
||||
)}
|
||||
>
|
||||
{changedValue && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-unsaved">
|
||||
{t("unsavedChanges")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-full flex-col gap-2 sm:flex-row sm:items-center md:w-auto">
|
||||
{changedValue && (
|
||||
<Button
|
||||
onClick={onCancel}
|
||||
variant="outline"
|
||||
disabled={isLoading}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{t("button.undo", { ns: "common" })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={saveToConfig}
|
||||
variant="select"
|
||||
disabled={!changedValue || isLoading}
|
||||
className="flex min-w-36 flex-1 gap-2"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<ActivityIndicator className="h-4 w-4" />
|
||||
{t("button.saving", { ns: "common" })}
|
||||
</>
|
||||
) : (
|
||||
t("button.save", { ns: "common" })
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<RestartDialog
|
||||
isOpen={restartDialogOpen}
|
||||
onClose={() => setRestartDialogOpen(false)}
|
||||
onRestart={() => sendRestart("restart")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import ActivityIndicator from "@/components/indicators/activity-indicator";
|
||||
import Heading from "@/components/ui/heading";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import useSWR from "swr";
|
||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||
import {
|
||||
SettingsGroupCard,
|
||||
SplitCardRow,
|
||||
} from "@/components/card/SettingsGroupCard";
|
||||
import {
|
||||
SingleSectionPage,
|
||||
type SettingsPageProps,
|
||||
} from "@/views/settings/SingleSectionPage";
|
||||
import FrigatePlusCurrentModelSummary from "@/views/settings/components/FrigatePlusCurrentModelSummary";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function SystemDetectionModelSettingsView(
|
||||
props: SettingsPageProps,
|
||||
) {
|
||||
const { t } = useTranslation(["config/global", "views/settings"]);
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const [showModelForm, setShowModelForm] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!config) {
|
||||
return <ActivityIndicator />;
|
||||
}
|
||||
|
||||
const isPlusModelActive = Boolean(config?.model?.plus?.id);
|
||||
|
||||
if (!isPlusModelActive || showModelForm) {
|
||||
return <SingleSectionPage sectionKey="model" level="global" {...props} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex size-full max-w-5xl flex-col lg:pr-2">
|
||||
<div className="mb-5 flex items-center justify-between gap-4">
|
||||
<div className="flex flex-col">
|
||||
<Heading as="h4">{t("model.label", { ns: "config/global" })}</Heading>
|
||||
<div className="my-1 text-sm text-muted-foreground">
|
||||
{t("model.description", { ns: "config/global" })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<SettingsGroupCard
|
||||
title={t("detectionModel.plusActive.title", { ns: "views/settings" })}
|
||||
>
|
||||
<SplitCardRow
|
||||
label={t("detectionModel.plusActive.label", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
description={t("detectionModel.plusActive.description", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
content={
|
||||
<div className="flex flex-col items-start gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate("/settings?page=frigateplus")}
|
||||
>
|
||||
{t("detectionModel.plusActive.goToFrigatePlus", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowModelForm(true)}
|
||||
>
|
||||
{t("detectionModel.plusActive.showModelForm", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SettingsGroupCard>
|
||||
|
||||
<FrigatePlusCurrentModelSummary plusModel={config.model.plus} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ReactNode } from "react";
|
||||
import {
|
||||
SettingsGroupCard,
|
||||
SplitCardRow,
|
||||
@@ -7,15 +8,26 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
type FrigatePlusCurrentModelSummaryProps = {
|
||||
plusModel: FrigateConfig["model"]["plus"];
|
||||
action?: ReactNode;
|
||||
};
|
||||
|
||||
export default function FrigatePlusCurrentModelSummary({
|
||||
plusModel,
|
||||
action,
|
||||
}: FrigatePlusCurrentModelSummaryProps) {
|
||||
const { t } = useTranslation("views/settings");
|
||||
|
||||
const title = action ? (
|
||||
<div className="flex w-full items-center justify-between gap-3">
|
||||
<span>{t("frigatePlus.cardTitles.currentModel")}</span>
|
||||
{action}
|
||||
</div>
|
||||
) : (
|
||||
t("frigatePlus.cardTitles.currentModel")
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsGroupCard title={t("frigatePlus.cardTitles.currentModel")}>
|
||||
<SettingsGroupCard title={title}>
|
||||
{!plusModel && (
|
||||
<p className="text-muted-foreground">
|
||||
{t("frigatePlus.modelInfo.noModelLoaded")}
|
||||
|
||||
Reference in New Issue
Block a user