-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassify-camera-webserver.ts
357 lines (296 loc) · 13 KB
/
classify-camera-webserver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import sharp from 'sharp';
import express = require('express');
import socketIO from 'socket.io';
import http from 'http';
import Path from 'path';
import OpenAI from "openai";
import { highlightAnomalyInImage } from "./helpers";
import { Ffmpeg, ICamera, ImageClassifier, Imagesnap, LinuxImpulseRunner, ModelInformation, RunnerHelloHasAnomaly } from 'edge-impulse-linux';
import { ips } from './get-ips';
import looksSame from 'looks-same';
if (!process.env.OPENAI_API_KEY) {
console.log('Missing OPENAI_API_KEY');
process.exit(1);
}
const BASE_PROMPT = `This image was flagged by an anomaly detection system, the anomaly is flagged in red. Can you explain what is off in this picture?
Reply with a very short response.`;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
try {
// Required arguments:
// arg 2: Path to the model file. e.g. /tmp/model.eim
// arg 3: Name of the camera device, see output of `gst-device-monitor-1.0`. e.g. "HD Pro Webcam C920"
// Optional arguments:
// arg 4: desired FPS. e.g. 20, default 30
// arg 5: desired capture width. e.g. 320, default 640
// arg 6: desired capture height. e.g. 200, default 480
// arg 7: webserver port. e.g. 4999, default 4912
const argModelFile = process.argv[2];
const argCamDevice = process.argv[3];
const fps = process.argv[4] ? Number(process.argv[4]) : 30;
const dimensions = (process.argv[5] && process.argv[6]) ? {
width: Number(process.argv[5]),
height: Number(process.argv[6])
} : {
width: 640,
height: 480
};
const port = process.argv[7] ? Number(process.argv[7]) : (process.env.PORT ? Number(process.env.PORT) : 4912);
if (!argModelFile) {
console.log('Missing one argument (model file)');
process.exit(1);
}
let runner = new LinuxImpulseRunner(argModelFile);
let model = await runner.init();
let labels = model.modelParameters.labels;
if (model.modelParameters.has_anomaly !== RunnerHelloHasAnomaly.VisualGMM) {
console.log('ERR: This repository expects a visual anomaly detection model');
process.exit(1);
}
labels.push('anomaly');
console.log('Starting the image classifier for',
model.project.owner + ' / ' + model.project.name, '(v' + model.project.deploy_version + ')');
console.log('Parameters',
'image size', model.modelParameters.image_input_width + 'x' + model.modelParameters.image_input_height + ' px (' +
model.modelParameters.image_channel_count + ' channels)',
'classes', labels);
// select a camera... you can implement this interface for other targets :-)
let camera: ICamera;
if (process.platform === 'darwin') {
camera = new Imagesnap();
}
else if (process.platform === 'linux') {
camera = new Ffmpeg(false /* verbose */);
}
else {
throw new Error('Unsupported platform "' + process.platform + '"');
}
await camera.init();
const devices = await camera.listDevices();
if (devices.length === 0) {
throw new Error('Cannot find any webcams');
}
if (devices.length > 1 && !argCamDevice) {
throw new Error('Multiple cameras found (' + devices.map(n => '"' + n + '"').join(', ') + '), add ' +
'the camera to use to this script (node classify-camera-webserver.js model.eim cameraname)');
}
let device = argCamDevice || devices[0];
console.log('Using camera', device, 'starting...');
await camera.start({
device: device,
intervalMs: 1000 / fps,
dimensions: dimensions
});
camera.on('error', error => {
console.log('camera error', error);
process.exit(1);
});
console.log('Connected to camera');
let imageClassifier = new ImageClassifier(runner, camera);
await imageClassifier.start();
let webserverPort = await startWebServer(model, camera, imageClassifier, port);
console.log('');
console.log('Want to see a feed of the camera and live classification in your browser? ' +
'Go to http://' + (ips.length > 0 ? ips[0].address : 'localhost') + ':' + webserverPort);
console.log('');
}
catch (ex) {
console.error(ex);
process.exit(1);
}
})();
function startWebServer(model: ModelInformation, camera: ICamera, imgClassifier: ImageClassifier, port: number) {
let openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const app = express();
app.use(express.static(Path.join(__dirname, '..', 'public')));
const server = new http.Server(app);
const io = socketIO(server);
let cascadeEnabled = false;
let prompt = BASE_PROMPT;
let minDiffBetweenAnomalies = 40;
// you can also get the actual image being classified from 'imageClassifier.on("result")',
// but then you're limited by the inference speed.
// here we get a direct feed from the camera so we guarantee the fps that we set earlier.
let lastFrameOriginalResolution: Buffer | undefined;
let processingFrame = false;
camera.on('snapshot', async (data) => {
if (processingFrame) return;
lastFrameOriginalResolution = data;
processingFrame = true;
let img;
if (model.modelParameters.image_channel_count === 3) {
img = sharp(data).resize({
height: model.modelParameters.image_input_height,
width: model.modelParameters.image_input_width
});
}
else {
img = sharp(data).resize({
height: model.modelParameters.image_input_height,
width: model.modelParameters.image_input_width
}).toColourspace('b-w');
}
io.emit('image', {
img: 'data:image/jpeg;base64,' + (await img.jpeg().toBuffer()).toString('base64')
});
processingFrame = false;
});
let isRunningOpenAI = false;
let imgToSendToOpenAI: Buffer = Buffer.from([ ]);
let imgToSendToOpenAICollected = new Date();
let lastImgSentToOpenAI: Buffer | undefined;
let anomalySeen = false;
let predictionCounter = 0;
(async () => {
const sleep = (ms: number) => new Promise<void>(res => setTimeout(res, ms));
while (1) {
await sleep(500);
if (!anomalySeen) continue;
if (!cascadeEnabled) continue;
if (!prompt) continue;
try {
let imgForOpenAI = imgToSendToOpenAI;
let imgForOpenAICollected = imgToSendToOpenAICollected;
if (lastImgSentToOpenAI) {
if ((await looksSame(lastImgSentToOpenAI, imgForOpenAI, {
tolerance: minDiffBetweenAnomalies,
antialiasingTolerance: minDiffBetweenAnomalies,
strict: false,
})).equal) {
console.log('Anomaly detected, but image is too similar to last analyzed anomaly');
io.emit('anomaly', {
message: 'Anomaly detected, but image is too similar to last analyzed anomaly',
});
anomalySeen = false;
continue;
}
}
lastImgSentToOpenAI = imgForOpenAI;
let predictionIx = predictionCounter++;
let now = Date.now();
io.emit('prediction-begin', {
id: predictionIx,
image: 'data:image/jpeg;base64,' + (imgForOpenAI.toString('base64')),
timestamp: imgForOpenAICollected.toISOString(),
});
console.log('Anomaly detected, asking GPT-4o...');
io.emit('anomaly', {
message: 'Anomaly detected, asking GPT-4o...',
});
const resp = await openai.chat.completions.create({
model: 'gpt-4o-2024-05-13',
messages: [{
role: 'user',
content: [{
type: 'text',
text: prompt,
}, {
type: 'image_url',
image_url: {
url: 'data:image/jpeg;base64,' + (imgForOpenAI.toString('base64')),
detail: 'auto'
}
}]
}]
});
if (resp.choices.length !== 1) {
throw new Error('Expected choices to have 1 item (' + JSON.stringify(resp) + ')');
}
if (resp.choices[0].message.role !== 'assistant') {
throw new Error('Expected choices[0].message.role to equal "assistant" (' + JSON.stringify(resp) + ')');
}
if (typeof resp.choices[0].message.content !== 'string') {
throw new Error('Expected choices[0].message.content to be a string (' + JSON.stringify(resp) + ')');
}
console.log('Response:', resp.choices[0].message.content);
console.log('');
io.emit('anomaly', {
message: 'Response: ' + resp.choices[0].message.content,
});
io.emit('prediction-done', {
id: predictionIx,
response: resp.choices[0].message.content,
timeMs: Date.now() - now,
});
}
catch (ex) {
console.log('OpenAI failed:', ex);
console.log('');
}
}
})();
imgClassifier.on('result', async (ev, timeMs, imgAsJpg) => {
io.emit('classification', {
modelType: model.modelParameters.model_type,
result: ev.result,
timeMs: timeMs,
additionalInfo: ev.info,
});
if (lastFrameOriginalResolution) {
imgToSendToOpenAICollected = new Date();
imgToSendToOpenAI = await highlightAnomalyInImage(lastFrameOriginalResolution, ev, model);
if (ev.result.visual_anomaly_grid && ev.result.visual_anomaly_grid.length > 0) {
await sharp(imgToSendToOpenAI).toFile('tmp.png');
}
}
if ((ev.result.visual_anomaly_grid || []).length > 0 && !isRunningOpenAI) {
anomalySeen = true;
}
else {
anomalySeen = false;
}
});
io.on('connection', socket => {
socket.emit('hello', {
projectName: model.project.owner + ' / ' + model.project.name,
thresholds: model.modelParameters.thresholds,
});
socket.on('cascade-enable', () => {
cascadeEnabled = true;
});
socket.on('cascade-disable', () => {
cascadeEnabled = false;
});
socket.on('prompt', (promptArg: string) => {
console.log('Prompt is now:', promptArg);
prompt = promptArg;
});
socket.on('min-diff-between-anomalies', (minDiffBetweenAnomaliesArg: number) => {
if (!isNaN(minDiffBetweenAnomaliesArg) && minDiffBetweenAnomaliesArg >= 0) {
console.log('Min. diff between anomalies is now:', minDiffBetweenAnomaliesArg);
minDiffBetweenAnomalies = minDiffBetweenAnomaliesArg;
}
});
socket.on('threshold-override', async (ev: {
id: number,
key: string,
value: number,
}) => {
try {
process.stdout.write(`Updating threshold for block ID ${ev.id}, key ${ev.key} to: ${ev.value}... `);
let thresholdObj = (model.modelParameters.thresholds || []).find(x => x.id === ev.id);
if (!thresholdObj) {
throw new Error(`Cannot find threshold with ID ` + ev.id);
}
let obj: { [k: string]: string | number } = {
id: ev.id,
};
obj.type = thresholdObj.type;
obj[ev.key] = ev.value;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
await imgClassifier.getRunner().setLearnBlockThreshold(<any>obj);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(<any>thresholdObj)[ev.key] = ev.value;
console.log(`OK`);
}
catch (ex) {
console.log('Failed to set threshold:', ex);
}
});
});
return new Promise<number>((resolve) => {
server.listen(port, process.env.HOST || '0.0.0.0', async () => {
resolve(port);
});
});
}