@7365admin1/layer-common 4.97.1-staging.623 → 4.97.1-staging.625

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ <!--
2
+ New smart detection, in two steps.
3
+ Step 1: name it, pick a camera, drag a box over the area to watch on the camera's latest picture.
4
+ Step 2: list the results (what the area can look like) and which ones should raise an alert.
5
+ The box is saved as fractions of the picture (0..1) so it stays right at any screen size.
6
+ -->
7
+ <template>
8
+ <v-dialog :model-value="modelValue" max-width="820" scrollable persistent @update:model-value="close">
9
+ <v-card>
10
+ <v-card-title class="d-flex align-center">
11
+ <span class="flex-grow-1">New smart detection</span>
12
+ <v-btn icon="mdi-close" variant="text" aria-label="Close" @click="close(false)" />
13
+ </v-card-title>
14
+ <v-card-text>
15
+ <v-stepper-header class="mb-3 elevation-0">
16
+ <v-stepper-item :complete="step > 1" :value="1" title="Area" :color="step === 1 ? 'primary' : undefined" />
17
+ <v-divider />
18
+ <v-stepper-item :value="2" title="Results" :color="step === 2 ? 'primary' : undefined" />
19
+ </v-stepper-header>
20
+
21
+ <template v-if="step === 1">
22
+ <p class="hero-muted">
23
+ Teach the engine to tell apart what an area looks like, for example a bin area that is clean or has rubbish.
24
+ Give it a name, pick the camera, then drag a box over the area on the picture.
25
+ </p>
26
+ <v-row dense>
27
+ <v-col cols="12" sm="6">
28
+ <v-text-field v-model="name" label="Name (e.g. bin_area)" density="comfortable" :error-messages="nameShown" hint="Letters, numbers and underscores. Spaces become underscores." persistent-hint />
29
+ </v-col>
30
+ <v-col cols="12" sm="6">
31
+ <v-select
32
+ v-model="camera"
33
+ :items="cameras"
34
+ item-title="name"
35
+ item-value="name"
36
+ label="Camera"
37
+ density="comfortable"
38
+ :loading="camLoading"
39
+ :no-data-text="camError ? 'Cameras could not be read' : 'This engine has no cameras yet'"
40
+ />
41
+ </v-col>
42
+ </v-row>
43
+
44
+ <template v-if="camera">
45
+ <v-progress-linear v-if="imgLoading" indeterminate class="mb-2" />
46
+ <div
47
+ ref="stage"
48
+ class="cctv-dc__stage"
49
+ role="img"
50
+ :aria-label="`Latest picture from ${camera}. Drag to draw a box over the area.`"
51
+ @pointerdown.prevent="down"
52
+ @pointermove="move"
53
+ @pointerup="up"
54
+ @pointercancel="up"
55
+ >
56
+ <img v-if="image" :src="image" alt="" class="cctv-dc__img" draggable="false" />
57
+ <div v-else-if="!imgLoading" class="cctv-dc__none">No picture available yet. The engine may be offline. You can still draw a box.</div>
58
+ <div v-if="box" class="cctv-dc__box" :style="boxStyle" />
59
+ </div>
60
+ <div class="hero-muted mt-1">
61
+ <template v-if="cropIsUsable(crop)">Area set. Drag again to change it.</template>
62
+ <template v-else>Press and drag on the picture to draw a box around the area. Make it big enough to see clearly.</template>
63
+ </div>
64
+ <CctvEngineNotice v-if="imgError" class="mt-2" tone="info" :error="imgError" title="The latest picture could not be loaded" body="The engine may be offline. You can still draw a box on the grey area." />
65
+ </template>
66
+ </template>
67
+
68
+ <template v-else>
69
+ <p class="hero-muted">
70
+ What can this area look like? Add each possible result as a word, for example <b>clean</b> and <b>rubbish</b>.
71
+ Choose which results should raise an alert and send a notification.
72
+ </p>
73
+ <v-combobox
74
+ :model-value="states"
75
+ multiple
76
+ chips
77
+ closable-chips
78
+ label="Results (press Enter after each)"
79
+ density="comfortable"
80
+ :error-messages="resultsShown"
81
+ hint="At least 2, at most 10. Letters, numbers and underscores."
82
+ persistent-hint
83
+ @update:model-value="setStates"
84
+ />
85
+ <v-select
86
+ v-model="alertStates"
87
+ :items="states"
88
+ multiple
89
+ chips
90
+ clearable
91
+ label="Alert me when the result is..."
92
+ density="comfortable"
93
+ class="mt-3"
94
+ hint="Optional. Leave empty to only record the results."
95
+ persistent-hint
96
+ />
97
+ <v-alert type="info" variant="tonal" density="compact" class="mt-4" icon="mdi-information-outline">
98
+ What happens next: the engine now saves photos of this area when something moves and every 5 minutes.
99
+ Sort at least {{ MIN_PHOTOS_PER_RESULT }} photos into each result, then press Teach.
100
+ </v-alert>
101
+ </template>
102
+
103
+ <CctvEngineNotice v-if="error" class="mt-3" :error="error" />
104
+ </v-card-text>
105
+ <v-card-actions>
106
+ <v-btn v-if="step === 2" variant="text" @click="step = 1">Back</v-btn>
107
+ <v-spacer />
108
+ <v-btn variant="text" @click="close(false)">Cancel</v-btn>
109
+ <v-btn v-if="step === 1" color="primary" :disabled="!!step1Problem" @click="step = 2">Next</v-btn>
110
+ <v-btn v-else color="primary" :loading="saving" :disabled="!!resultsProblemText || saving" @click="create">Create</v-btn>
111
+ </v-card-actions>
112
+ <div v-if="step === 1 && step1Problem" class="hero-muted px-6 pb-3">{{ step1Problem }}</div>
113
+ </v-card>
114
+ </v-dialog>
115
+ </template>
116
+
117
+ <script setup lang="ts">
118
+ import { computed, onBeforeUnmount, ref, watch } from "vue";
119
+ import {
120
+ cropFromDrag, cropIsUsable, DEFAULT_RESULTS, detectionNameProblem, MIN_PHOTOS_PER_RESULT, resultsProblem, toWord,
121
+ type TCrop,
122
+ } from "../../utils/cctv-engine";
123
+
124
+ const props = defineProps<{ modelValue: boolean; engine: string }>();
125
+ const emit = defineEmits<{ (e: "update:modelValue", v: boolean): void; (e: "created", message: string): void }>();
126
+ const { listCameras, latestImage, createClassifier } = useCctvEngine();
127
+
128
+ const step = ref(1);
129
+ const name = ref("");
130
+ const camera = ref("");
131
+ const cameras = ref<any[]>([]);
132
+ const camLoading = ref(false);
133
+ const camError = ref<unknown>(null);
134
+ const image = ref("");
135
+ const imgLoading = ref(false);
136
+ const imgError = ref<unknown>(null);
137
+ const crop = ref<TCrop | null>(null);
138
+ const states = ref<string[]>([...DEFAULT_RESULTS]);
139
+ const alertStates = ref<string[]>(["rubbish"]);
140
+ const saving = ref(false);
141
+ const error = ref<unknown>(null);
142
+ const stage = ref<HTMLElement | null>(null);
143
+
144
+ const nameProblem = computed(() => detectionNameProblem(name.value));
145
+ const nameShown = computed(() => (name.value ? nameProblem.value : ""));
146
+ const step1Problem = computed(() =>
147
+ nameProblem.value || (!camera.value ? "Pick a camera." : !cropIsUsable(crop.value) ? "Draw a box over the area on the picture." : ""),
148
+ );
149
+ const resultsProblemText = computed(() => resultsProblem(states.value, alertStates.value));
150
+ const resultsShown = computed(() => (states.value.length ? resultsProblemText.value : ""));
151
+
152
+ // ---- drawing the box (pointer events, so mouse, pen and touch all work)
153
+ const dragFrom = ref<{ x: number; y: number } | null>(null);
154
+ const box = computed(() => crop.value);
155
+ const boxStyle = computed(() => {
156
+ const c = box.value!;
157
+ return { left: c[0] * 100 + "%", top: c[1] * 100 + "%", width: (c[2] - c[0]) * 100 + "%", height: (c[3] - c[1]) * 100 + "%" };
158
+ });
159
+ function down(ev: PointerEvent) {
160
+ dragFrom.value = { x: ev.clientX, y: ev.clientY };
161
+ (ev.currentTarget as HTMLElement).setPointerCapture?.(ev.pointerId);
162
+ crop.value = null;
163
+ }
164
+ function move(ev: PointerEvent) {
165
+ if (!dragFrom.value || !stage.value) return;
166
+ crop.value = cropFromDrag(stage.value.getBoundingClientRect(), dragFrom.value, { x: ev.clientX, y: ev.clientY });
167
+ }
168
+ function up(ev: PointerEvent) {
169
+ if (dragFrom.value) move(ev);
170
+ dragFrom.value = null;
171
+ }
172
+
173
+ function setStates(v: string[]) {
174
+ const clean = [...new Set((v ?? []).map(toWord).filter(Boolean))];
175
+ states.value = clean;
176
+ alertStates.value = alertStates.value.filter((a) => clean.includes(a));
177
+ }
178
+
179
+ function freeImage() {
180
+ if (image.value) URL.revokeObjectURL(image.value);
181
+ image.value = "";
182
+ }
183
+
184
+ async function loadCameras() {
185
+ cameras.value = [];
186
+ camError.value = null;
187
+ camLoading.value = true;
188
+ try {
189
+ cameras.value = ((await listCameras(props.engine)) as any)?.items ?? [];
190
+ if (cameras.value.length === 1) camera.value = cameras.value[0].name;
191
+ } catch (e) {
192
+ camError.value = e;
193
+ } finally {
194
+ camLoading.value = false;
195
+ }
196
+ }
197
+ async function loadImage() {
198
+ freeImage();
199
+ crop.value = null;
200
+ imgError.value = null;
201
+ if (!camera.value) return;
202
+ imgLoading.value = true;
203
+ try {
204
+ image.value = await latestImage(props.engine, camera.value);
205
+ } catch (e) {
206
+ imgError.value = e;
207
+ } finally {
208
+ imgLoading.value = false;
209
+ }
210
+ }
211
+
212
+ async function create() {
213
+ saving.value = true;
214
+ error.value = null;
215
+ try {
216
+ const res: any = await createClassifier(props.engine, {
217
+ name: toWord(name.value),
218
+ camera: camera.value,
219
+ crop: crop.value,
220
+ states: states.value,
221
+ alertStates: alertStates.value,
222
+ });
223
+ emit("created", res?.message || "Smart detection created. The engine is now collecting photos of this area.");
224
+ close(false);
225
+ } catch (e) {
226
+ error.value = e;
227
+ } finally {
228
+ saving.value = false;
229
+ }
230
+ }
231
+
232
+ function reset() {
233
+ step.value = 1;
234
+ name.value = camera.value = "";
235
+ crop.value = null;
236
+ states.value = [...DEFAULT_RESULTS];
237
+ alertStates.value = ["rubbish"];
238
+ error.value = null;
239
+ freeImage();
240
+ }
241
+ function close(v: boolean) {
242
+ emit("update:modelValue", v);
243
+ }
244
+
245
+ watch(() => props.modelValue, (open) => {
246
+ if (open) {
247
+ reset();
248
+ loadCameras();
249
+ }
250
+ }, { immediate: true });
251
+ watch(camera, loadImage);
252
+ onBeforeUnmount(freeImage);
253
+ </script>
254
+
255
+ <style scoped>
256
+ .cctv-dc__stage { position: relative; background: #111; border-radius: 10px; overflow: hidden; min-height: 180px; user-select: none; cursor: crosshair; touch-action: none; }
257
+ .cctv-dc__img { width: 100%; display: block; pointer-events: none; }
258
+ .cctv-dc__none { color: #ddd; padding: 60px 16px; text-align: center; font-size: 13px; aspect-ratio: 16 / 9; }
259
+ .cctv-dc__box { position: absolute; border: 2px solid #fff; background: rgba(30, 136, 229, 0.3); box-shadow: 0 0 0 1px #1e88e5; pointer-events: none; }
260
+ </style>
@@ -0,0 +1,266 @@
1
+ <!--
2
+ One smart detection: sort the photos the engine collected into results, then teach it.
3
+ "Waiting" photos have no result yet (the engine's guess is shown as a hint). Press a result's button to sort one,
4
+ or tick several and discard them. Each result needs at least 5 sorted photos before Teach is available.
5
+ Every action shows the server's own message.
6
+ -->
7
+ <template>
8
+ <div>
9
+ <div class="d-flex align-center flex-wrap ga-2 mb-2">
10
+ <v-btn variant="text" prepend-icon="mdi-arrow-left" @click="$emit('back')">All smart detections</v-btn>
11
+ <v-spacer />
12
+ <v-btn variant="text" color="error" prepend-icon="mdi-delete-outline" @click="confirmDelete = true">Delete</v-btn>
13
+ </div>
14
+
15
+ <v-progress-linear v-if="loading" indeterminate />
16
+ <CctvEngineNotice v-else-if="error" :error="error" retry @retry="load" />
17
+ <template v-else-if="data">
18
+ <h3 class="d-flex align-center flex-wrap ga-2">
19
+ {{ data.name }}
20
+ <v-chip size="small" label :color="status.color">{{ status.title }}</v-chip>
21
+ </h3>
22
+ <p class="hero-muted">Watching camera <b>{{ data.camera }}</b>. Results that raise an alert: <b>{{ (data.alertStates ?? []).join(", ") || "none" }}</b>.</p>
23
+
24
+ <!-- Teach -->
25
+ <v-card variant="tonal" class="pa-3 mb-4">
26
+ <div class="d-flex align-center flex-wrap ga-3">
27
+ <v-btn color="primary" prepend-icon="mdi-school-outline" :disabled="!!blocked || teaching || busy" :loading="teaching" @click="teach">Teach</v-btn>
28
+ <span class="hero-muted flex-grow-1">
29
+ <template v-if="teaching">The engine is learning. This can take a few minutes; this page updates when it is done.</template>
30
+ <template v-else-if="blocked">{{ blocked }}</template>
31
+ <template v-else>Every result has enough photos. Press Teach so the engine learns from them.</template>
32
+ </span>
33
+ </div>
34
+ </v-card>
35
+
36
+ <!-- Alert results -->
37
+ <v-row dense class="mb-2">
38
+ <v-col cols="12" sm="8" md="6">
39
+ <v-select v-model="alerts" :items="data.states" multiple chips clearable label="Alert me when the result is..." density="comfortable" hide-details />
40
+ </v-col>
41
+ <v-col cols="12" sm="4" class="d-flex align-center">
42
+ <v-btn variant="tonal" :disabled="!alertsChanged || busy" @click="saveAlerts">Save alerts</v-btn>
43
+ </v-col>
44
+ </v-row>
45
+
46
+ <!-- Waiting photos -->
47
+ <h4 class="mt-4 d-flex align-center flex-wrap ga-2">
48
+ Waiting to be sorted ({{ data.waiting.length }})
49
+ <v-btn v-if="data.waiting.length" size="x-small" variant="text" @click="toggleAll">{{ picked.size === data.waiting.length ? "Clear selection" : "Select all" }}</v-btn>
50
+ <v-btn v-if="picked.size" size="small" color="error" variant="tonal" prepend-icon="mdi-delete-outline" :disabled="busy" @click="confirmDiscard = true">Discard selected ({{ picked.size }})</v-btn>
51
+ </h4>
52
+ <p v-if="!data.waiting.length" class="hero-muted">
53
+ Nothing waiting. The engine saves a new photo of this area when something moves and every 5 minutes; they will appear here.
54
+ </p>
55
+ <v-row v-else dense>
56
+ <v-col v-for="p in data.waiting" :key="p.file" cols="6" sm="4" md="3">
57
+ <v-card variant="outlined" :class="{ 'cctv-dd__picked': picked.has(p.file) }">
58
+ <div class="cctv-dd__thumb" @click="togglePick(p.file)">
59
+ <img v-if="thumbs[key(p.file)]" :src="thumbs[key(p.file)]" :alt="`Waiting photo from ${when(p.at)}`" />
60
+ <v-icon v-else icon="mdi-image-outline" size="28" />
61
+ <v-checkbox-btn :model-value="picked.has(p.file)" class="cctv-dd__check" density="compact" aria-label="Select photo" @click.stop @update:model-value="togglePick(p.file)" />
62
+ </div>
63
+ <div class="pa-2">
64
+ <div class="hero-muted">{{ when(p.at) }}</div>
65
+ <div v-if="p.guess" class="hero-muted">Engine thinks: <b>{{ p.guess }}</b><template v-if="typeof p.score === 'number'"> ({{ pct(p.score) }})</template></div>
66
+ <div class="d-flex flex-wrap ga-1 mt-1">
67
+ <v-btn v-for="s in data.states" :key="s" size="x-small" variant="tonal" :color="s === p.guess ? 'primary' : undefined" :disabled="busy" @click="sort(p.file, s)">{{ s }}</v-btn>
68
+ </div>
69
+ </div>
70
+ </v-card>
71
+ </v-col>
72
+ </v-row>
73
+
74
+ <!-- Sorted photos -->
75
+ <h4 class="mt-6">Sorted photos</h4>
76
+ <div v-for="s in data.states" :key="s" class="mt-3">
77
+ <div class="d-flex align-center flex-wrap ga-2">
78
+ <b>{{ s }}</b>
79
+ <v-chip size="x-small" label :color="count(s) >= MIN_PHOTOS_PER_RESULT ? 'success' : 'warning'">{{ count(s) }} of {{ MIN_PHOTOS_PER_RESULT }} needed</v-chip>
80
+ <v-chip v-if="(data.alertStates ?? []).includes(s)" size="x-small" label color="error">Alert</v-chip>
81
+ </div>
82
+ <p v-if="!(data.sorted?.[s] ?? []).length" class="hero-muted">No photos sorted as {{ s }} yet.</p>
83
+ <v-row v-else dense class="mt-0">
84
+ <v-col v-for="f in data.sorted[s]" :key="f" cols="4" sm="3" md="2">
85
+ <div class="cctv-dd__thumb cctv-dd__thumb--sm">
86
+ <img v-if="thumbs[key(f, s)]" :src="thumbs[key(f, s)]" :alt="`Photo sorted as ${s}`" />
87
+ <v-icon v-else icon="mdi-image-outline" size="24" />
88
+ <v-btn icon="mdi-close" size="x-small" variant="flat" class="cctv-dd__remove" :disabled="busy" :aria-label="`Remove this photo from ${s}`" @click="discard([f], s)" />
89
+ </div>
90
+ </v-col>
91
+ </v-row>
92
+ </div>
93
+ </template>
94
+
95
+ <v-dialog v-model="confirmDiscard" max-width="420">
96
+ <v-card title="Discard these photos?">
97
+ <v-card-text>{{ picked.size }} waiting photo(s) will be deleted from the engine. This cannot be undone.</v-card-text>
98
+ <v-card-actions><v-spacer /><v-btn variant="text" @click="confirmDiscard = false">Keep them</v-btn><v-btn color="error" @click="discardPicked">Discard</v-btn></v-card-actions>
99
+ </v-card>
100
+ </v-dialog>
101
+ <v-dialog v-model="confirmDelete" max-width="460">
102
+ <v-card :title="`Delete ${name}?`">
103
+ <v-card-text>This removes the smart detection and all its photos and training from the engine. Past results already recorded in Events stay. This cannot be undone.</v-card-text>
104
+ <v-card-actions><v-spacer /><v-btn variant="text" @click="confirmDelete = false">Keep it</v-btn><v-btn color="error" :loading="busy" @click="remove">Delete</v-btn></v-card-actions>
105
+ </v-card>
106
+ </v-dialog>
107
+
108
+ <v-snackbar v-model="snack.open" :color="snack.error ? 'error' : undefined" timeout="6000" multi-line>{{ snack.text }}</v-snackbar>
109
+ </div>
110
+ </template>
111
+
112
+ <script setup lang="ts">
113
+ import { computed, onBeforeUnmount, reactive, ref, watch } from "vue";
114
+ import { classifierStatus, cctvNotice, MIN_PHOTOS_PER_RESULT, teachProblem } from "../../utils/cctv-engine";
115
+
116
+ const props = defineProps<{ engine: string; name: string; teaching?: boolean }>();
117
+ const emit = defineEmits<{ (e: "back"): void; (e: "changed"): void; (e: "taught"): void; (e: "deleted"): void }>();
118
+ const { classifierPhotos, classifierPhoto, sortClassifierPhoto, discardClassifierPhotos, updateClassifier, trainClassifier, deleteClassifier } = useCctvEngine();
119
+
120
+ const data = ref<any>(null);
121
+ const loading = ref(false);
122
+ const error = ref<unknown>(null);
123
+ const busy = ref(false);
124
+ const thumbs = ref<Record<string, string>>({});
125
+ const picked = ref<Set<string>>(new Set());
126
+ const alerts = ref<string[]>([]);
127
+ const confirmDiscard = ref(false);
128
+ const confirmDelete = ref(false);
129
+ const snack = reactive({ open: false, text: "", error: false });
130
+
131
+ const key = (file: string, state?: string) => `${state ?? "_"}/${file}`;
132
+ const count = (s: string) => data.value?.counts?.[s] ?? data.value?.sorted?.[s]?.length ?? 0;
133
+ const when = (v?: string | null) => (v ? new Date(v).toLocaleString() : "Time not known");
134
+ const pct = (s: number) => `${Math.round(s <= 1 ? s * 100 : s)}%`;
135
+ const blocked = computed(() => (data.value ? teachProblem({ states: data.value.states, counts: data.value.counts }) : ""));
136
+ const status = computed(() => classifierStatus({ ...data.value, waiting: data.value?.waiting?.length ?? 0 }, { teaching: props.teaching }));
137
+ const alertsChanged = computed(() => {
138
+ const a = [...alerts.value].sort().join();
139
+ return a !== [...(data.value?.alertStates ?? [])].sort().join();
140
+ });
141
+
142
+ function say(text: string, isError = false) {
143
+ Object.assign(snack, { open: true, text, error: isError });
144
+ }
145
+ const errText = (e: any) => String(e?.data?.message || "").trim() || cctvNotice(e).body;
146
+
147
+ // ---- photos (fetched as blobs because an image tag cannot send the sign-in; 4 at a time)
148
+ async function loadThumbs() {
149
+ const todo: { k: string; file: string; state?: string }[] = [];
150
+ for (const p of data.value.waiting) if (!thumbs.value[key(p.file)]) todo.push({ k: key(p.file), file: p.file });
151
+ for (const [s, files] of Object.entries<string[]>(data.value.sorted ?? {}))
152
+ for (const f of files) if (!thumbs.value[key(f, s)]) todo.push({ k: key(f, s), file: f, state: s });
153
+ let i = 0;
154
+ const worker = async () => {
155
+ while (i < todo.length) {
156
+ const t = todo[i++];
157
+ try {
158
+ const url = await classifierPhoto(props.engine, props.name, t.file, t.state);
159
+ thumbs.value = { ...thumbs.value, [t.k]: url };
160
+ } catch {
161
+ /* placeholder stays */
162
+ }
163
+ }
164
+ };
165
+ await Promise.all([worker(), worker(), worker(), worker()]);
166
+ }
167
+ function pruneThumbs() {
168
+ const live = new Set<string>([
169
+ ...data.value.waiting.map((p: any) => key(p.file)),
170
+ ...Object.entries<string[]>(data.value.sorted ?? {}).flatMap(([s, fs]) => fs.map((f) => key(f, s))),
171
+ ]);
172
+ for (const [k, u] of Object.entries(thumbs.value)) {
173
+ if (!live.has(k)) {
174
+ URL.revokeObjectURL(u);
175
+ delete thumbs.value[k];
176
+ }
177
+ }
178
+ }
179
+ function freeThumbs() {
180
+ Object.values(thumbs.value).forEach((u) => URL.revokeObjectURL(u));
181
+ thumbs.value = {};
182
+ }
183
+
184
+ async function load(quiet = false) {
185
+ if (!quiet) loading.value = true;
186
+ error.value = null;
187
+ try {
188
+ const res: any = await classifierPhotos(props.engine, props.name);
189
+ data.value = { ...res, waiting: res?.waiting ?? [], sorted: res?.sorted ?? {}, states: res?.states ?? [] };
190
+ alerts.value = [...(res?.alertStates ?? [])];
191
+ picked.value = new Set([...picked.value].filter((f) => data.value.waiting.some((p: any) => p.file === f)));
192
+ pruneThumbs();
193
+ loading.value = false;
194
+ loadThumbs();
195
+ } catch (e) {
196
+ error.value = e;
197
+ } finally {
198
+ loading.value = false;
199
+ }
200
+ }
201
+
202
+ // ---- actions: each says what the server said
203
+ async function act(fn: () => Promise<any>, fallback: string, reload = true) {
204
+ busy.value = true;
205
+ try {
206
+ const res: any = await fn();
207
+ say(res?.message || fallback);
208
+ if (reload) {
209
+ await load(true);
210
+ emit("changed");
211
+ }
212
+ return true;
213
+ } catch (e) {
214
+ say(errText(e), true);
215
+ return false;
216
+ } finally {
217
+ busy.value = false;
218
+ }
219
+ }
220
+ const sort = (file: string, state: string) => act(() => sortClassifierPhoto(props.engine, props.name, file, state), `Sorted as ${state}.`);
221
+ const discard = (files: string[], state?: string) => act(() => discardClassifierPhotos(props.engine, props.name, files, state), "Photo removed.");
222
+ async function discardPicked() {
223
+ confirmDiscard.value = false;
224
+ await discard([...picked.value]);
225
+ }
226
+ const saveAlerts = () => act(() => updateClassifier(props.engine, props.name, { alertStates: alerts.value }), "Alerts saved.");
227
+ async function teach() {
228
+ if (await act(() => trainClassifier(props.engine, props.name), "Teaching has started.", false)) emit("taught");
229
+ }
230
+ async function remove() {
231
+ busy.value = true;
232
+ try {
233
+ await deleteClassifier(props.engine, props.name);
234
+ confirmDelete.value = false;
235
+ emit("deleted");
236
+ } catch (e) {
237
+ confirmDelete.value = false;
238
+ say(errText(e), true);
239
+ } finally {
240
+ busy.value = false;
241
+ }
242
+ }
243
+
244
+ const togglePick = (f: string) => {
245
+ const s = new Set(picked.value);
246
+ s.has(f) ? s.delete(f) : s.add(f);
247
+ picked.value = s;
248
+ };
249
+ const toggleAll = () => {
250
+ picked.value = picked.value.size === data.value.waiting.length ? new Set() : new Set(data.value.waiting.map((p: any) => p.file));
251
+ };
252
+
253
+ // When Teach finishes (the list stops saying "teaching"), refresh so the status and counts are current.
254
+ watch(() => props.teaching, (now, was) => was && !now && load(true));
255
+ watch(() => props.name, () => { freeThumbs(); load(); }, { immediate: true });
256
+ onBeforeUnmount(freeThumbs);
257
+ </script>
258
+
259
+ <style scoped>
260
+ .cctv-dd__thumb { position: relative; aspect-ratio: 16 / 9; background: #111; display: flex; align-items: center; justify-content: center; color: #aaa; overflow: hidden; cursor: pointer; }
261
+ .cctv-dd__thumb--sm { cursor: default; }
262
+ .cctv-dd__thumb img { width: 100%; height: 100%; object-fit: cover; }
263
+ .cctv-dd__check { position: absolute; top: 0; left: 0; background: rgba(255, 255, 255, 0.8); border-radius: 0 0 6px 0; }
264
+ .cctv-dd__remove { position: absolute; top: 2px; right: 2px; }
265
+ .cctv-dd__picked { outline: 2px solid #1e88e5; }
266
+ </style>
@@ -0,0 +1,135 @@
1
+ <!--
2
+ Smart detection: teach the engine to recognise what an area looks like (clean or rubbish, door open or shut...).
3
+ Lists the detections for an engine with where each one is up to; open one to sort its photos and teach it.
4
+ Needs the "Manage zones and smart detection" permission (cctv-engine:manage-zones).
5
+ -->
6
+ <template>
7
+ <div>
8
+ <CctvEngineCameraPicker v-model:engine="engine" :site="site" no-camera />
9
+
10
+ <template v-if="engine">
11
+ <template v-if="selected">
12
+ <CctvEngineDetectionDetail
13
+ :key="engine + selected"
14
+ :engine="engine"
15
+ :name="selected"
16
+ :teaching="teachingNames.has(selected)"
17
+ @back="selected = ''"
18
+ @changed="load(true)"
19
+ @taught="startTeaching(selected)"
20
+ @deleted="onDeleted"
21
+ />
22
+ </template>
23
+ <template v-else>
24
+ <div class="d-flex align-center flex-wrap ga-2 mt-3">
25
+ <p class="hero-muted flex-grow-1 mb-0">
26
+ Teach the engine to tell what an area looks like, for example a bin area that is clean or full of rubbish.
27
+ It can raise an alert for the results you choose.
28
+ </p>
29
+ <v-btn color="primary" prepend-icon="mdi-plus" @click="creating = true">New smart detection</v-btn>
30
+ </div>
31
+
32
+ <v-progress-linear v-if="loading" indeterminate class="mt-3" />
33
+ <CctvEngineNotice v-else-if="error" class="mt-3" :error="error" retry @retry="load()" />
34
+ <CctvEngineNotice
35
+ v-else-if="!items.length"
36
+ class="mt-3"
37
+ title="No smart detections yet"
38
+ body="Press New smart detection, draw a box over an area on a camera, and name the results you want to tell apart."
39
+ />
40
+ <v-row v-else class="mt-1">
41
+ <v-col v-for="c in items" :key="c.name" cols="12" sm="6" md="4">
42
+ <v-card variant="outlined" class="h-100" @click="selected = c.name">
43
+ <v-card-title class="text-subtitle-1">{{ c.name }}</v-card-title>
44
+ <v-card-text>
45
+ <v-chip size="small" label :color="statusOf(c).color" class="mb-2">{{ statusOf(c).title }}</v-chip>
46
+ <div class="hero-muted">Camera: {{ c.camera }}</div>
47
+ <div class="hero-muted">Results: {{ (c.states ?? []).join(", ") }}</div>
48
+ <div class="hero-muted">Alerts on: {{ (c.alertStates ?? []).join(", ") || "none" }}</div>
49
+ <div v-if="c.engineUnreachable" class="text-warning mt-1">The engine could not be reached, so this may be out of date.</div>
50
+ </v-card-text>
51
+ </v-card>
52
+ </v-col>
53
+ </v-row>
54
+ </template>
55
+
56
+ <CctvEngineDetectionCreate v-model="creating" :engine="engine" @created="onCreated" />
57
+ </template>
58
+
59
+ <v-snackbar v-model="snack.open" timeout="6000" multi-line>{{ snack.text }}</v-snackbar>
60
+ </div>
61
+ </template>
62
+
63
+ <script setup lang="ts">
64
+ import { onBeforeUnmount, reactive, ref, watch } from "vue";
65
+ import { classifierStatus, type TClassifier } from "../../utils/cctv-engine";
66
+
67
+ defineProps<{ site: string; access?: unknown }>();
68
+ const { listClassifiers } = useCctvEngine();
69
+
70
+ const engine = ref("");
71
+ const items = ref<TClassifier[]>([]);
72
+ const loading = ref(false);
73
+ const error = ref<unknown>(null);
74
+ const selected = ref("");
75
+ const creating = ref(false);
76
+ const snack = reactive({ open: false, text: "" });
77
+
78
+ // Teach runs on the engine in the background. Remember which were started here and check every 10 s until each
79
+ // one's last-trained time moves on (ponytail: only trainings started on this screen are tracked).
80
+ const teachingNames = ref<Set<string>>(new Set());
81
+ const taughtBefore = new Map<string, string | null>();
82
+ let timer: ReturnType<typeof setInterval> | undefined;
83
+
84
+ const statusOf = (c: TClassifier) => classifierStatus(c, { teaching: teachingNames.value.has(c.name) });
85
+
86
+ async function load(quiet = false) {
87
+ if (!quiet) loading.value = true;
88
+ error.value = null;
89
+ try {
90
+ const res: any = await listClassifiers(engine.value);
91
+ items.value = res?.items ?? [];
92
+ checkTeaching();
93
+ } catch (e) {
94
+ error.value = e;
95
+ if (!quiet) items.value = [];
96
+ } finally {
97
+ loading.value = false;
98
+ }
99
+ }
100
+
101
+ function startTeaching(name: string) {
102
+ taughtBefore.set(name, items.value.find((c) => c.name === name)?.training?.lastTrainedAt ?? null);
103
+ teachingNames.value = new Set(teachingNames.value).add(name);
104
+ clearInterval(timer);
105
+ timer = setInterval(() => load(true), 10000);
106
+ }
107
+ function checkTeaching() {
108
+ const still = new Set<string>();
109
+ for (const name of teachingNames.value) {
110
+ const c = items.value.find((x) => x.name === name);
111
+ if (c && (c.training?.lastTrainedAt ?? null) === taughtBefore.get(name)) still.add(name);
112
+ }
113
+ teachingNames.value = still;
114
+ if (!still.size) clearInterval(timer);
115
+ }
116
+
117
+ function onCreated(message: string) {
118
+ Object.assign(snack, { open: true, text: message });
119
+ load(true);
120
+ }
121
+ function onDeleted() {
122
+ Object.assign(snack, { open: true, text: "Smart detection deleted." });
123
+ selected.value = "";
124
+ load(true);
125
+ }
126
+
127
+ watch(engine, () => {
128
+ selected.value = "";
129
+ items.value = [];
130
+ teachingNames.value = new Set();
131
+ clearInterval(timer);
132
+ if (engine.value) load();
133
+ });
134
+ onBeforeUnmount(() => clearInterval(timer));
135
+ </script>
@@ -0,0 +1,108 @@
1
+ <!--
2
+ One event in a dialog: picture, clip (when there is one), and the facts. Used by Events and Smart search.
3
+ Pass the event row to open it; it emits `close` when dismissed. Smart detection results have a photo and no clip.
4
+ -->
5
+ <template>
6
+ <v-dialog :model-value="!!event" max-width="900" scrollable @update:model-value="(v: boolean) => !v && $emit('close')">
7
+ <v-card v-if="event">
8
+ <v-card-title class="d-flex align-center">
9
+ <span class="flex-grow-1">{{ title }}</span>
10
+ <v-btn icon="mdi-close" variant="text" aria-label="Close" @click="$emit('close')" />
11
+ </v-card-title>
12
+ <v-card-text>
13
+ <v-progress-linear v-if="mediaLoading" indeterminate />
14
+ <img v-if="snapshot" :src="snapshot" :alt="`Snapshot of ${title}`" class="cctv-ev__img" />
15
+ <CctvEngineNotice v-else-if="!mediaLoading && event.hasSnapshot === false" title="No picture saved" body="The engine did not keep a snapshot for this event." />
16
+ <CctvEngineNotice v-if="mediaError" :error="mediaError" />
17
+
18
+ <template v-if="!isClassification">
19
+ <video v-if="clip" :src="clip" controls autoplay class="cctv-ev__img mt-3" />
20
+ <v-btn v-else-if="event.hasClip" class="mt-3" prepend-icon="mdi-play" :loading="clipLoading" @click="loadClip">Play clip</v-btn>
21
+ <div v-else class="hero-muted mt-3">No video clip was saved for this event.</div>
22
+ </template>
23
+
24
+ <v-table density="compact" class="mt-4">
25
+ <tbody>
26
+ <tr><th>Camera</th><td>{{ event.camera }}</td></tr>
27
+ <tr><th>When</th><td>{{ when(event.startTime) }}<template v-if="event.endTime"> to {{ when(event.endTime) }}</template></td></tr>
28
+ <template v-if="isClassification">
29
+ <tr><th>Result</th><td>{{ event.label }}</td></tr>
30
+ <tr><th>Smart detection</th><td>{{ event.subLabel }}</td></tr>
31
+ </template>
32
+ <tr v-else><th>Object</th><td>{{ event.label }}<template v-if="event.subLabel"> ({{ event.subLabel }})</template></td></tr>
33
+ <tr v-if="event.faceName"><th>Face</th><td>{{ event.faceName }}</td></tr>
34
+ <tr v-if="event.plate"><th>Plate</th><td>{{ event.plate }}</td></tr>
35
+ <tr v-if="!isClassification"><th>Zones</th><td>{{ (event.zones ?? []).join(", ") || "None" }}<template v-if="(event.enteredZones ?? []).length"> (entered: {{ event.enteredZones.join(" then ") }})</template></td></tr>
36
+ <tr><th>Confidence</th><td>{{ scoreText(event.score) }}</td></tr>
37
+ <tr v-if="event.incident"><th>Incident</th><td>An incident report was created for this alert.</td></tr>
38
+ </tbody>
39
+ </v-table>
40
+ </v-card-text>
41
+ </v-card>
42
+ </v-dialog>
43
+ </template>
44
+
45
+ <script setup lang="ts">
46
+ import { computed, onBeforeUnmount, ref, watch } from "vue";
47
+ import { classificationTitle } from "../../utils/cctv-engine";
48
+
49
+ const props = defineProps<{ event: any | null }>();
50
+ defineEmits<{ (e: "close"): void }>();
51
+ const { eventSnapshot, eventClip } = useCctvEngine();
52
+
53
+ const snapshot = ref("");
54
+ const clip = ref("");
55
+ const mediaLoading = ref(false);
56
+ const clipLoading = ref(false);
57
+ const mediaError = ref<unknown>(null);
58
+
59
+ const isClassification = computed(() => props.event?.kind === "classification");
60
+ const title = computed(() => {
61
+ const e = props.event;
62
+ if (!e) return "";
63
+ if (e.kind === "classification") return classificationTitle(e);
64
+ return [e.label, e.faceName && `- ${e.faceName}`, e.plate && `- ${e.plate}`].filter(Boolean).join(" ") || "Event";
65
+ });
66
+ const when = (v?: string) => (v ? new Date(v).toLocaleString() : "");
67
+ const scoreText = (s?: number) => (typeof s === "number" ? `${Math.round(s <= 1 ? s * 100 : s)}%` : "Not given");
68
+
69
+ function freeMedia() {
70
+ if (snapshot.value) URL.revokeObjectURL(snapshot.value);
71
+ if (clip.value) URL.revokeObjectURL(clip.value);
72
+ snapshot.value = clip.value = "";
73
+ mediaError.value = null;
74
+ }
75
+ async function show(e: any | null) {
76
+ freeMedia();
77
+ if (!e || e.hasSnapshot === false) return;
78
+ mediaLoading.value = true;
79
+ try {
80
+ const url = await eventSnapshot(e._id);
81
+ // The person may have closed it or opened another one while this loaded.
82
+ if (props.event?._id === e._id) snapshot.value = url;
83
+ else URL.revokeObjectURL(url);
84
+ } catch (err) {
85
+ mediaError.value = err;
86
+ } finally {
87
+ mediaLoading.value = false;
88
+ }
89
+ }
90
+ async function loadClip() {
91
+ clipLoading.value = true;
92
+ mediaError.value = null;
93
+ try {
94
+ clip.value = await eventClip(props.event._id);
95
+ } catch (err) {
96
+ mediaError.value = err;
97
+ } finally {
98
+ clipLoading.value = false;
99
+ }
100
+ }
101
+
102
+ watch(() => props.event, show, { immediate: true });
103
+ onBeforeUnmount(freeMedia);
104
+ </script>
105
+
106
+ <style scoped>
107
+ .cctv-ev__img { width: 100%; max-height: 60vh; object-fit: contain; background: #000; border-radius: 8px; }
108
+ </style>
@@ -39,47 +39,17 @@
39
39
  <v-pagination v-if="pages > 1" v-model="page" :length="pages" :total-visible="smAndDown ? 3 : 7" class="mt-2" @update:model-value="load" />
40
40
  <div v-if="pageRange" class="hero-muted text-center">{{ pageRange }}</div>
41
41
 
42
- <v-dialog v-model="detailOpen" max-width="900" scrollable>
43
- <v-card v-if="current">
44
- <v-card-title class="d-flex align-center">
45
- <span class="flex-grow-1">{{ titleOf(current) }}</span>
46
- <v-btn icon="mdi-close" variant="text" aria-label="Close" @click="closeDetail" />
47
- </v-card-title>
48
- <v-card-text>
49
- <v-progress-linear v-if="mediaLoading" indeterminate />
50
- <img v-if="snapshot" :src="snapshot" :alt="`Snapshot of ${titleOf(current)}`" class="cctv-ev__img" />
51
- <CctvEngineNotice v-else-if="!mediaLoading && current.hasSnapshot === false" title="No picture saved" body="The engine did not keep a snapshot for this event." />
52
- <CctvEngineNotice v-if="mediaError" :error="mediaError" />
53
-
54
- <video v-if="clip" :src="clip" controls autoplay class="cctv-ev__img mt-3" />
55
- <v-btn v-else-if="current.hasClip" class="mt-3" prepend-icon="mdi-play" :loading="clipLoading" @click="loadClip">Play clip</v-btn>
56
- <div v-else class="hero-muted mt-3">No video clip was saved for this event.</div>
57
-
58
- <v-table density="compact" class="mt-4">
59
- <tbody>
60
- <tr><th>Camera</th><td>{{ current.camera }}</td></tr>
61
- <tr><th>When</th><td>{{ when(current.startTime) }}<template v-if="current.endTime"> to {{ when(current.endTime) }}</template></td></tr>
62
- <tr><th>Object</th><td>{{ current.label }}<template v-if="current.subLabel"> ({{ current.subLabel }})</template></td></tr>
63
- <tr v-if="current.faceName"><th>Face</th><td>{{ current.faceName }}</td></tr>
64
- <tr v-if="current.plate"><th>Plate</th><td>{{ current.plate }}</td></tr>
65
- <tr><th>Zones</th><td>{{ (current.zones ?? []).join(", ") || "None" }}<template v-if="(current.enteredZones ?? []).length"> (entered: {{ current.enteredZones.join(" then ") }})</template></td></tr>
66
- <tr><th>Confidence</th><td>{{ scoreText(current.score) }}</td></tr>
67
- <tr v-if="current.incident"><th>Incident</th><td>An incident report was created for this alert.</td></tr>
68
- </tbody>
69
- </v-table>
70
- </v-card-text>
71
- </v-card>
72
- </v-dialog>
42
+ <CctvEngineEventDetail :event="current" @close="current = null" />
73
43
  </div>
74
44
  </template>
75
45
 
76
46
  <script setup lang="ts">
77
- import { computed, onBeforeUnmount, reactive, ref } from "vue";
47
+ import { computed, reactive, ref } from "vue";
78
48
  import { useDisplay } from "vuetify";
79
- import { EVENT_KINDS, EVENT_SEVERITIES, type TEventFilters } from "../../utils/cctv-engine";
49
+ import { classificationTitle, EVENT_KINDS, EVENT_SEVERITIES, type TEventFilters } from "../../utils/cctv-engine";
80
50
 
81
51
  const props = defineProps<{ site: string; access?: unknown }>();
82
- const { listEvents, eventSnapshot, eventClip } = useCctvEngine();
52
+ const { listEvents } = useCctvEngine();
83
53
  const { smAndDown } = useDisplay();
84
54
 
85
55
  const f = reactive<TEventFilters>({});
@@ -117,59 +87,11 @@ function clear() {
117
87
 
118
88
  const kindTitle = (k: string) => EVENT_KINDS.find((x) => x.value === k)?.title ?? k;
119
89
  const when = (v?: string) => (v ? new Date(v).toLocaleString() : "");
120
- const scoreText = (s?: number) => (typeof s === "number" ? `${Math.round(s <= 1 ? s * 100 : s)}%` : "Not given");
121
- const titleOf = (e: any) => [e.label, e.faceName && `- ${e.faceName}`, e.plate && `- ${e.plate}`].filter(Boolean).join(" ") || "Event";
90
+ const titleOf = (e: any) => e.kind === "classification" ? classificationTitle(e) : [e.label, e.faceName && `- ${e.faceName}`, e.plate && `- ${e.plate}`].filter(Boolean).join(" ") || "Event";
122
91
  const subtitleOf = (e: any) => `${e.camera} - ${when(e.startTime)}${(e.zones ?? []).length ? ` - ${e.zones.join(", ")}` : ""}`;
123
92
 
124
- // ---- detail
125
- const detailOpen = ref(false);
126
93
  const current = ref<any>(null);
127
- const snapshot = ref("");
128
- const clip = ref("");
129
- const mediaLoading = ref(false);
130
- const clipLoading = ref(false);
131
- const mediaError = ref<unknown>(null);
132
-
133
- function freeMedia() {
134
- if (snapshot.value) URL.revokeObjectURL(snapshot.value);
135
- if (clip.value) URL.revokeObjectURL(clip.value);
136
- snapshot.value = clip.value = "";
137
- mediaError.value = null;
138
- }
139
- async function open(e: any) {
140
- freeMedia();
141
- current.value = e;
142
- detailOpen.value = true;
143
- if (e.hasSnapshot === false) return;
144
- mediaLoading.value = true;
145
- try {
146
- snapshot.value = await eventSnapshot(e._id);
147
- } catch (err) {
148
- mediaError.value = err;
149
- } finally {
150
- mediaLoading.value = false;
151
- }
152
- }
153
- async function loadClip() {
154
- clipLoading.value = true;
155
- mediaError.value = null;
156
- try {
157
- clip.value = await eventClip(current.value._id);
158
- } catch (err) {
159
- mediaError.value = err;
160
- } finally {
161
- clipLoading.value = false;
162
- }
163
- }
164
- function closeDetail() {
165
- detailOpen.value = false;
166
- freeMedia();
167
- }
168
- onBeforeUnmount(freeMedia);
94
+ const open = (e: any) => (current.value = e);
169
95
 
170
96
  load();
171
97
  </script>
172
-
173
- <style scoped>
174
- .cctv-ev__img { width: 100%; max-height: 60vh; object-fit: contain; background: #000; border-radius: 8px; }
175
- </style>
@@ -0,0 +1,177 @@
1
+ <!--
2
+ Smart search: describe what you are looking for in words ("person with a red umbrella") and the site's own
3
+ engine finds the best matching pictures from past events. Free; nothing leaves the site's engine.
4
+ Opens a result in the same detail window the Events screen uses.
5
+ -->
6
+ <template>
7
+ <div>
8
+ <CctvEngineCameraPicker v-model:engine="engine" :site="site" no-camera />
9
+
10
+ <template v-if="engine">
11
+ <v-form class="mt-3" @submit.prevent="run">
12
+ <v-row dense>
13
+ <v-col cols="12" md="7">
14
+ <v-text-field
15
+ v-model="text"
16
+ label="Describe what you are looking for"
17
+ placeholder="e.g. person with a red umbrella, white van, bicycle"
18
+ density="comfortable"
19
+ prepend-inner-icon="mdi-text-search"
20
+ clearable
21
+ hide-details
22
+ autofocus
23
+ />
24
+ </v-col>
25
+ <v-col cols="8" md="3">
26
+ <v-select
27
+ v-model="camera"
28
+ :items="cameras"
29
+ item-title="name"
30
+ item-value="name"
31
+ label="Camera (optional)"
32
+ density="comfortable"
33
+ clearable
34
+ hide-details
35
+ :no-data-text="'No cameras found for this engine'"
36
+ />
37
+ </v-col>
38
+ <v-col cols="4" md="2" class="d-flex align-center">
39
+ <v-btn type="submit" color="primary" block :loading="loading" :disabled="loading">Search</v-btn>
40
+ </v-col>
41
+ </v-row>
42
+ </v-form>
43
+ <div class="hero-muted mt-1">Free to use. The search runs on the engine at your site, so pictures stay there.</div>
44
+
45
+ <CctvEngineNotice v-if="problem" class="mt-3" tone="info" title="Check what you typed" :body="problem" />
46
+ <v-progress-linear v-if="loading" indeterminate class="mt-3" />
47
+ <CctvEngineNotice
48
+ v-else-if="searchOff"
49
+ class="mt-3"
50
+ tone="info"
51
+ title="Smart search is not switched on yet"
52
+ :body="searchOff"
53
+ />
54
+ <CctvEngineNotice v-else-if="error" class="mt-3" :error="error" retry @retry="run" />
55
+ <CctvEngineNotice
56
+ v-else-if="searched && !items.length"
57
+ class="mt-3"
58
+ title="Nothing matched"
59
+ body="Try fewer or simpler words (for example 'van' instead of 'white delivery van'), pick a different camera, or check the engine is Online in Engines & health."
60
+ />
61
+ <CctvEngineNotice
62
+ v-else-if="!searched"
63
+ class="mt-3"
64
+ title="Search the pictures your cameras have saved"
65
+ body="Type what you want to find, for example 'person with a red umbrella', and press Search. The best matches come first."
66
+ />
67
+
68
+ <v-row v-if="items.length" class="mt-1">
69
+ <v-col v-for="e in items" :key="e._id" cols="6" sm="4" md="3">
70
+ <v-card variant="outlined" class="cctv-sr__card" @click="current = e">
71
+ <div class="cctv-sr__thumb">
72
+ <img v-if="thumbs[e._id]" :src="thumbs[e._id]" :alt="`Picture of ${e.label}`" />
73
+ <v-icon v-else icon="mdi-image-off-outline" size="32" />
74
+ </div>
75
+ <div class="pa-2">
76
+ <div class="font-weight-medium text-truncate">{{ classificationTitle(e) || "Event" }}</div>
77
+ <div class="hero-muted text-truncate">{{ e.camera }}</div>
78
+ <div class="hero-muted">{{ when(e.startTime) }}</div>
79
+ </div>
80
+ </v-card>
81
+ </v-col>
82
+ </v-row>
83
+ </template>
84
+
85
+ <CctvEngineEventDetail :event="current" @close="current = null" />
86
+ </div>
87
+ </template>
88
+
89
+ <script setup lang="ts">
90
+ import { onBeforeUnmount, ref, watch } from "vue";
91
+ import { buildSearchQuery, classificationTitle } from "../../utils/cctv-engine";
92
+
93
+ defineProps<{ site: string; access?: unknown }>();
94
+ const { listCameras, searchEvents, eventSnapshot } = useCctvEngine();
95
+
96
+ const engine = ref("");
97
+ const camera = ref<string | null>(null);
98
+ const cameras = ref<any[]>([]);
99
+ const text = ref("");
100
+ const items = ref<any[]>([]);
101
+ const thumbs = ref<Record<string, string>>({});
102
+ const loading = ref(false);
103
+ const searched = ref(false);
104
+ const problem = ref("");
105
+ const searchOff = ref("");
106
+ const error = ref<unknown>(null);
107
+ const current = ref<any>(null);
108
+
109
+ const when = (v?: string) => (v ? new Date(v).toLocaleString() : "");
110
+
111
+ function freeThumbs() {
112
+ Object.values(thumbs.value).forEach((u) => URL.revokeObjectURL(u));
113
+ thumbs.value = {};
114
+ }
115
+
116
+ async function run() {
117
+ problem.value = searchOff.value = "";
118
+ error.value = null;
119
+ const q = buildSearchQuery(text.value, camera.value);
120
+ if (!q.ok) {
121
+ problem.value = q.problem;
122
+ return;
123
+ }
124
+ loading.value = true;
125
+ freeThumbs();
126
+ try {
127
+ const res: any = await searchEvents(engine.value, q.query);
128
+ items.value = res?.items ?? [];
129
+ searched.value = true;
130
+ loadThumbs(items.value);
131
+ } catch (e: any) {
132
+ items.value = [];
133
+ // "Not switched on" is an answer, not a failure: show the server's own words as an info notice.
134
+ if (e?.data?.code === "SEARCH_OFF") searchOff.value = String(e.data.message || "Smart search is not switched on in this camera engine yet. Ask your Seven365 contact to switch it on.");
135
+ else error.value = e;
136
+ } finally {
137
+ loading.value = false;
138
+ }
139
+ }
140
+
141
+ // Pictures need the signed-in session, so each is fetched as a blob; a failed one just shows a placeholder.
142
+ async function loadThumbs(rows: any[]) {
143
+ const shown = items.value;
144
+ await Promise.all(
145
+ rows.filter((e) => e.hasSnapshot !== false).map(async (e) => {
146
+ try {
147
+ const url = await eventSnapshot(e._id);
148
+ if (items.value === shown) thumbs.value = { ...thumbs.value, [e._id]: url };
149
+ else URL.revokeObjectURL(url);
150
+ } catch {
151
+ /* placeholder stays */
152
+ }
153
+ }),
154
+ );
155
+ }
156
+
157
+ watch(engine, async (id) => {
158
+ camera.value = null;
159
+ cameras.value = [];
160
+ items.value = [];
161
+ searched.value = false;
162
+ freeThumbs();
163
+ if (!id) return;
164
+ try {
165
+ cameras.value = ((await listCameras(id)) as any)?.items ?? [];
166
+ } catch {
167
+ /* the camera filter is optional; search still works */
168
+ }
169
+ });
170
+ onBeforeUnmount(freeThumbs);
171
+ </script>
172
+
173
+ <style scoped>
174
+ .cctv-sr__card { cursor: pointer; height: 100%; }
175
+ .cctv-sr__thumb { aspect-ratio: 16 / 9; background: #111; display: flex; align-items: center; justify-content: center; color: #aaa; overflow: hidden; }
176
+ .cctv-sr__thumb img { width: 100%; height: 100%; object-fit: cover; }
177
+ </style>
@@ -8,7 +8,7 @@
8
8
  <div class="cctv-shell">
9
9
  <h2 class="hero-title">CCTV Engine</h2>
10
10
  <p class="hero-muted mb-3">
11
- Cameras analysed by the iSecure365 engine at the site: live view, events, playback, zones, plates and alerts.
11
+ Cameras analysed by the iSecure365 engine at the site: live view, events, smart search, playback, zones, smart detection, plates and alerts.
12
12
  This sits next to the CCTV wall and does not change it.
13
13
  </p>
14
14
 
@@ -77,6 +77,8 @@ const VIEWS: Record<TCctvSection, any> = {
77
77
  faces: resolveComponent("CctvEngineFaces"),
78
78
  alerts: resolveComponent("CctvEngineAlerts"),
79
79
  engines: resolveComponent("CctvEngineEngines"),
80
+ search: resolveComponent("CctvEngineSearch"),
81
+ detections: resolveComponent("CctvEngineDetections"),
80
82
  };
81
83
  const view = computed(() => VIEWS[current.value]);
82
84
 
@@ -68,6 +68,27 @@ export default function useCctvEngine() {
68
68
  const eventSnapshot = (id: string) => blobUrl(`/api/cctv-events/${id}/snapshot.jpg`);
69
69
  const eventClip = (id: string) => blobUrl(`/api/cctv-events/${id}/clip.mp4`);
70
70
 
71
+ // ---- smart search (same event rows as listEvents, best match first)
72
+ const searchEvents = (engineId: string, query: Record<string, string | number>) =>
73
+ api(`/api/cctv-engines/${engineId}/search`, { method: "GET", query });
74
+
75
+ // ---- smart detection (custom training). Photos are read as blobs like snapshots.
76
+ const cls = (engineId: string, name?: string) =>
77
+ `/api/cctv-engines/${engineId}/classifiers${name ? "/" + enc(name) : ""}`;
78
+ const listClassifiers = (engineId: string) => api(cls(engineId), { method: "GET" });
79
+ const createClassifier = (engineId: string, body: Record<string, any>) => api(cls(engineId), { method: "POST", body });
80
+ const updateClassifier = (engineId: string, name: string, body: { alertStates: string[] }) =>
81
+ api(cls(engineId, name), { method: "PATCH", body });
82
+ const deleteClassifier = (engineId: string, name: string) => api(cls(engineId, name), { method: "DELETE" });
83
+ const classifierPhotos = (engineId: string, name: string) => api(`${cls(engineId, name)}/photos`, { method: "GET" });
84
+ const classifierPhoto = (engineId: string, name: string, file: string, state?: string) =>
85
+ blobUrl(`${cls(engineId, name)}/photo`, state ? { file, state } : { file });
86
+ const sortClassifierPhoto = (engineId: string, name: string, file: string, state: string) =>
87
+ api(`${cls(engineId, name)}/sort`, { method: "POST", body: { file, state } });
88
+ const discardClassifierPhotos = (engineId: string, name: string, files: string[], state?: string) =>
89
+ api(`${cls(engineId, name)}/discard`, { method: "POST", body: state ? { files, state } : { files } });
90
+ const trainClassifier = (engineId: string, name: string) => api(`${cls(engineId, name)}/train`, { method: "POST" });
91
+
71
92
  // ---- zones & wrong-way rules
72
93
  const getZones = (engineId: string, camera: string) => api(`${cam(engineId, camera)}/zones`, { method: "GET" });
73
94
  const saveZones = (engineId: string, camera: string, body: TZonesBody) =>
@@ -111,6 +132,9 @@ export default function useCctvEngine() {
111
132
  webrtcAnswer, blobUrl, latestImage,
112
133
  listRecordings, cameraClip, createExport, listExports, downloadExport,
113
134
  listEvents, getEvent, eventSnapshot, eventClip,
135
+ searchEvents,
136
+ listClassifiers, createClassifier, updateClassifier, deleteClassifier, classifierPhotos, classifierPhoto,
137
+ sortClassifierPhoto, discardClassifierPhotos, trainClassifier,
114
138
  getZones, saveZones, listWrongWayRules, createWrongWayRule, updateWrongWayRule, deleteWrongWayRule,
115
139
  listPlates, createPlate, updatePlate, deletePlate,
116
140
  listFaces, enrolFace, deleteFace,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.97.1-staging.623",
5
+ "version": "4.97.1-staging.625",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -39,6 +39,19 @@ export const LOOKUP_TIMEOUT_MS = 5000;
39
39
  */
40
40
  export const SEND_SITE = false;
41
41
 
42
+ /*
43
+ * Per app opt in, ahead of the switch above: an app that sets
44
+ * `runtimeConfig.public.roleFollowsSite` to true (or the env var
45
+ * `NUXT_PUBLIC_ROLE_FOLLOWS_SITE=true`) sends the site now, so its role follows
46
+ * the site while every other app keeps today's answer. Declare the key in the
47
+ * APP's own nuxt.config, never in this layer's, or an env var in any app's
48
+ * deploy could turn it on there. Absent or misspelled means off.
49
+ */
50
+ export function roleFollowsSite(): boolean {
51
+ const value = useRuntimeConfig().public.roleFollowsSite;
52
+ return SEND_SITE || value === true || value === "true";
53
+ }
54
+
42
55
  function bounded<T>(request: Promise<T>): Promise<T> {
43
56
  let timer: ReturnType<typeof setTimeout> | undefined;
44
57
  const timeout = new Promise<never>((_, reject) => {
@@ -111,7 +124,7 @@ export default defineNuxtPlugin(() => {
111
124
  // it when the answer can actually DIFFER: the first resolution, or a site
112
125
  // change while Q16 is on. While Q16 is held a site change re-asks the same
113
126
  // question, so the resolved role stays on screen and nothing flickers.
114
- if (resolvedFor === null || SEND_SITE) userAppRoleStatus.value = "loading";
127
+ if (resolvedFor === null || roleFollowsSite()) userAppRoleStatus.value = "loading";
115
128
  inFlightKey = key;
116
129
  inFlight = run(userId, site, staffOrg).finally(() => {
117
130
  inFlight = null;
@@ -139,7 +152,7 @@ export default defineNuxtPlugin(() => {
139
152
  // adds is Q16 itself. Sending `org` as well would change the fallback
140
153
  // too, and that is a separate change.
141
154
  const member = await bounded(
142
- getByUserType(userId, APP, undefined, SEND_SITE && site ? site : undefined),
155
+ getByUserType(userId, APP, undefined, roleFollowsSite() && site ? site : undefined),
143
156
  );
144
157
  hasMemberDocument = true;
145
158
  id.value = member.org ?? "";
@@ -29,7 +29,9 @@ export type TCctvSection =
29
29
  | "plates"
30
30
  | "faces"
31
31
  | "alerts"
32
- | "engines";
32
+ | "engines"
33
+ | "search"
34
+ | "detections";
33
35
 
34
36
  /** The menu, in the order people use it. `needs` is the permission the server enforces on that screen's routes. */
35
37
  export const CCTV_SECTIONS: { key: TCctvSection; title: string; icon: string; needs: TCctvPermission; face?: boolean }[] = [
@@ -37,7 +39,9 @@ export const CCTV_SECTIONS: { key: TCctvSection; title: string; icon: string; ne
37
39
  { key: "events", title: "Events", icon: "mdi-timeline-clock-outline", needs: CCTV_PERMISSIONS.viewEvents },
38
40
  { key: "playback", title: "Playback & export", icon: "mdi-play-box-outline", needs: CCTV_PERMISSIONS.viewEvents },
39
41
  { key: "zones", title: "Zones & wrong-way", icon: "mdi-vector-polygon", needs: CCTV_PERMISSIONS.manageZones },
42
+ { key: "search", title: "Smart search", icon: "mdi-text-search", needs: CCTV_PERMISSIONS.viewEvents },
40
43
  { key: "plates", title: "Known plates", icon: "mdi-car-info", needs: CCTV_PERMISSIONS.managePlates },
44
+ { key: "detections", title: "Smart detection", icon: "mdi-shape-plus-outline", needs: CCTV_PERMISSIONS.manageZones },
41
45
  { key: "faces", title: "Face library", icon: "mdi-face-recognition", needs: CCTV_PERMISSIONS.manageFaces, face: true },
42
46
  { key: "alerts", title: "Alerts", icon: "mdi-bell-ring-outline", needs: CCTV_PERMISSIONS.manageAlerts },
43
47
  { key: "engines", title: "Engines & health", icon: "mdi-server-network", needs: CCTV_PERMISSIONS.manageEngine },
@@ -84,6 +88,7 @@ export const EVENT_KINDS = [
84
88
  { value: "audio", title: "Sound heard" },
85
89
  { value: "wrong-way", title: "Wrong way" },
86
90
  { value: "review", title: "Review item" },
91
+ { value: "classification", title: "Smart detection" },
87
92
  ];
88
93
  export const EVENT_SEVERITIES = [
89
94
  { value: "alert", title: "Alert" },
@@ -328,3 +333,119 @@ export function summariseHealth(stats: THealthStats | null | undefined): THealth
328
333
  cameras: stats?.cameras ?? [],
329
334
  };
330
335
  }
336
+
337
+ // --------------------------------------------------------------------------- smart search
338
+
339
+ export const SEARCH_MIN = 2;
340
+ export const SEARCH_MAX = 200;
341
+
342
+ /** The words typed in the search box -> what the API takes, or the plain-words problem. */
343
+ export function buildSearchQuery(
344
+ text: string,
345
+ camera?: string | null,
346
+ limit = 24,
347
+ ): { ok: true; query: Record<string, string | number> } | { ok: false; problem: string } {
348
+ const q = (text ?? "").trim().replace(/\s+/g, " ");
349
+ if (q.length < SEARCH_MIN) return { ok: false, problem: `Type at least ${SEARCH_MIN} letters describing what you are looking for.` };
350
+ if (q.length > SEARCH_MAX) return { ok: false, problem: `Keep it under ${SEARCH_MAX} characters.` };
351
+ const query: Record<string, string | number> = { q, limit: Math.min(50, Math.max(1, Math.floor(limit) || 24)) };
352
+ if (camera) query.camera = camera;
353
+ return { ok: true, query };
354
+ }
355
+
356
+ /** Event heading: smart detections read "rubbish (bin_area)", everything else is the object name. */
357
+ export function classificationTitle(e: { kind?: string; label?: string; subLabel?: string }) {
358
+ return e.kind === "classification" && e.subLabel ? `${e.label} (${e.subLabel})` : String(e.label ?? "");
359
+ }
360
+
361
+ // --------------------------------------------------------------------------- smart detection (custom training)
362
+
363
+ export const MIN_PHOTOS_PER_RESULT = 5;
364
+ export const MAX_RESULTS = 10;
365
+ export const DEFAULT_RESULTS = ["clean", "rubbish"];
366
+ const WORD = /^[a-z0-9_]{1,40}$/;
367
+
368
+ /** What a person types ("Bin Area", "Rubbish!") -> the lowercase word the engine takes ("bin_area", "rubbish"). */
369
+ export const toWord = (v: string) =>
370
+ (v ?? "").toString().trim().toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "").slice(0, 40);
371
+
372
+ /** Plain-words problem with a detection name, or "". */
373
+ export function detectionNameProblem(name: string): string {
374
+ const w = toWord(name);
375
+ if (!w) return "Give the detection a short name, for example bin_area.";
376
+ if (!WORD.test(w)) return "Use letters, numbers and underscores only (up to 40).";
377
+ return "";
378
+ }
379
+
380
+ /** Plain-words problem with the list of results, or "". "none" is reserved by the engine. */
381
+ export function resultsProblem(states: readonly string[], alertStates: readonly string[] = []): string {
382
+ if (states.length < 2) return "Add at least two results, for example clean and rubbish.";
383
+ if (states.length > MAX_RESULTS) return `Use at most ${MAX_RESULTS} results.`;
384
+ if (new Set(states).size !== states.length) return "Each result must be different.";
385
+ if (states.some((s) => !WORD.test(s) || s === "none")) return 'Results use letters, numbers and underscores only, and "none" is not allowed.';
386
+ if (alertStates.some((a) => !states.includes(a))) return "An alert result must be one of the results.";
387
+ return "";
388
+ }
389
+
390
+ export type TCrop = [number, number, number, number];
391
+ export const MIN_CROP_SIDE = 0.03;
392
+
393
+ /** Mouse drag inside the picture box (pixels) -> [left, top, right, bottom] as 0..1 fractions, clamped and ordered. */
394
+ export function cropFromDrag(
395
+ box: { left: number; top: number; width: number; height: number },
396
+ from: { x: number; y: number },
397
+ to: { x: number; y: number },
398
+ ): TCrop {
399
+ const a = pointFromClick(box, from.x, from.y);
400
+ const b = pointFromClick(box, to.x, to.y);
401
+ return [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[0], b[0]), Math.max(a[1], b[1])];
402
+ }
403
+
404
+ /** Big enough to teach from (each side at least 3% of the picture). */
405
+ export const cropIsUsable = (c: readonly number[] | null | undefined) =>
406
+ !!c && c.length === 4 && c[2] - c[0] >= MIN_CROP_SIDE && c[3] - c[1] >= MIN_CROP_SIDE;
407
+
408
+ export type TClassifier = {
409
+ name: string;
410
+ camera?: string;
411
+ alertStates?: string[];
412
+ states?: string[];
413
+ counts?: Record<string, number>;
414
+ waiting?: number;
415
+ training?: { trained: boolean; lastTrainedAt: string | null; changedSinceTraining: boolean } | null;
416
+ engineUnreachable?: boolean;
417
+ };
418
+
419
+ /** Results that still need more sorted photos. */
420
+ export function shortResults(c: Pick<TClassifier, "states" | "counts">, min = MIN_PHOTOS_PER_RESULT) {
421
+ return (c.states ?? [])
422
+ .map((state) => ({ state, have: c.counts?.[state] ?? 0 }))
423
+ .filter((r) => r.have < min)
424
+ .map((r) => ({ ...r, need: min - r.have }));
425
+ }
426
+
427
+ /** Why Teach is not available yet, in plain words ("" = go ahead). */
428
+ export function teachProblem(c: Pick<TClassifier, "states" | "counts">, min = MIN_PHOTOS_PER_RESULT): string {
429
+ if (!(c.states ?? []).length) return "This detection has no results yet.";
430
+ const short = shortResults(c, min);
431
+ if (!short.length) return "";
432
+ return `Sort at least ${min} photos into each result first. Still needed: ${short.map((r) => `${r.state} (${r.have} of ${min})`).join(", ")}.`;
433
+ }
434
+
435
+ /** One chip for the list: what stage this detection is at. `teaching` = Teach was pressed on this screen and is running. */
436
+ export function classifierStatus(
437
+ c: TClassifier,
438
+ opts: { teaching?: boolean; date?: (iso: string) => string } = {},
439
+ ): { key: "teaching" | "collecting" | "sorting" | "ready" | "trained" | "changed"; title: string; color: string } {
440
+ const date = opts.date ?? ((iso: string) => new Date(iso).toLocaleDateString());
441
+ if (opts.teaching) return { key: "teaching", title: "Teaching...", color: "info" };
442
+ const t = c.training;
443
+ if (t?.trained) {
444
+ if (t.changedSinceTraining) return { key: "changed", title: "Changed since last teaching", color: "warning" };
445
+ return { key: "trained", title: t.lastTrainedAt ? `Trained on ${date(t.lastTrainedAt)}` : "Trained", color: "success" };
446
+ }
447
+ if (!teachProblem(c)) return { key: "ready", title: "Ready to teach", color: "primary" };
448
+ const waiting = c.waiting ?? 0;
449
+ if (waiting > 0) return { key: "sorting", title: `Needs sorting (${waiting} waiting)`, color: "warning" };
450
+ return { key: "collecting", title: "Collecting photos", color: "default" };
451
+ }