-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisualQA.html
More file actions
498 lines (435 loc) · 19.2 KB
/
Copy pathVisualQA.html
File metadata and controls
498 lines (435 loc) · 19.2 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Q&A App</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
padding: 20px;
background-color: #f0f0f0;
}
.controls, .io-areas {
display: flex;
gap: 10px;
align-items: center;
background-color: #fff;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.io-areas {
flex-direction: column;
align-items: stretch;
}
textarea {
width: 40em;
height: 80px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
#videoFeed {
width: 480px;
height: 360px;
border: 2px solid #333;
background-color: #000;
border-radius: 8px;
}
#startButton {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border: none;
border-radius: 4px;
color: white;
}
#startButton.start {
background-color: #28a745;
}
#startButton.stop {
background-color: #dc3545;
}
label {
font-weight: bold;
}
select {
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>Visual Q&A App</h1>
<div style="position: relative; width: 480px; height: 360px;">
<video id="videoFeed" autoplay playsinline style="position: absolute; top: 0; left: 0;"></video>
<canvas id="canvas" class="hidden"></canvas>
<canvas id="overlay" class="hidden"></canvas>
</div>
<div class="io-areas">
<div>
<label for="baseURL">Base API:</label><br>
<input id="baseURL" type="text" style="width: 40em" value="http://localhost:1234">
</div>
<div>
<label for="cameraSelect">Select Camera:</label><br>
<select id="cameraSelect" style="width: 40em; margin-bottom: 10px;">
<option value="">Loading cameras...</option>
</select>
</div>
<div>
<label for="instructionText">Ask Your Question (press Enter to send):</label><br>
<textarea id="instructionText" style="height: 4em; width: 40em" placeholder="Type your question and press Enter"></textarea>
</div>
<div>
<label for="responseText">AI Response:</label><br>
<textarea id="responseText" style="height: 8em; width: 40em" readonly placeholder="AI response will appear here..."></textarea>
</div>
</div>
<div class="controls">
<button id="startButton" class="start">Start</button>
</div>
<script>
const video = document.getElementById('videoFeed');
const canvas = document.getElementById('canvas');
const overlay = document.getElementById('overlay');
const baseURL = document.getElementById('baseURL');
const instructionText = document.getElementById('instructionText');
const responseText = document.getElementById('responseText');
const startButton = document.getElementById('startButton');
const cameraSelect = document.getElementById('cameraSelect');
let stream = null;
let isProcessing = false;
let currentDeviceId = null;
// Set default instruction
instructionText.value = "What do you see in this image?";
async function sendChatCompletionRequest(instruction, imageBase64URL) {
const response = await fetch(`${baseURL.value}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
max_tokens: 100,
temperature: 0.7,
stream: false,
messages: [
{ role: 'user', content: [
{ type: 'text', text: instruction },
{ type: 'image_url', image_url: { url: imageBase64URL } }
] },
],
model: "local-model"
})
});
if (!response.ok) {
const errorData = await response.text();
console.error("Chat Completion Error:", errorData);
return `Server error: ${response.status} - ${errorData}`;
}
const data = await response.json();
return data.choices[0].message.content;
}
// Get list of available cameras
async function getCameras() {
try {
responseText.value = "Requesting camera access...";
// First get user media access with minimal constraints
const tempStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
});
// Stop the temporary stream
tempStream.getTracks().forEach(track => track.stop());
// Then enumerate devices
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(device => device.kind === 'videoinput');
// Clear existing options
cameraSelect.innerHTML = '';
if (videoDevices.length === 0) {
cameraSelect.innerHTML = '<option value="">No cameras found</option>';
responseText.value = "No cameras found. Please connect a camera and refresh.";
return [];
}
// Add camera options
videoDevices.forEach((device, index) => {
const option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label || `Camera ${index + 1}`;
cameraSelect.appendChild(option);
});
// Select first camera by default and update currentDeviceId
if (videoDevices.length > 0) {
currentDeviceId = videoDevices[0].deviceId;
cameraSelect.value = currentDeviceId;
responseText.value = `Found ${videoDevices.length} camera(s). Ready to start.`;
}
return videoDevices;
} catch (error) {
console.error('Error getting cameras:', error);
let errorMessage = 'Error accessing camera: ';
if (error.name === 'NotAllowedError') {
errorMessage += 'Permission denied. Please allow camera access and refresh the page.';
} else if (error.name === 'NotFoundError') {
errorMessage += 'No camera found. Please connect a camera and refresh.';
} else {
errorMessage += error.message || 'Unknown error';
}
responseText.value = errorMessage;
cameraSelect.innerHTML = '<option value="">Error: Click to reload</option>';
cameraSelect.onclick = () => window.location.reload();
return [];
}
}
// Initialize camera with selected device
async function initCamera() {
if (!currentDeviceId) {
// If no device is selected but we have options, select the first one
if (cameraSelect.options.length > 0 && cameraSelect.value) {
currentDeviceId = cameraSelect.value;
} else {
responseText.value = "Please select a camera first";
return false;
}
}
try {
console.log('Initializing camera with device:', currentDeviceId);
responseText.value = "Initializing camera...";
// Stop any existing stream
if (stream) {
stream.getTracks().forEach(track => track.stop());
stream = null;
}
// Try to get user media with the selected device
const constraints = {
video: {
deviceId: { exact: currentDeviceId },
width: { ideal: 1280 },
height: { ideal: 720 }
},
audio: false
};
stream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = stream;
// Wait for the video to be ready
await new Promise((resolve) => {
const onLoaded = () => {
video.removeEventListener('loadedmetadata', onLoaded);
video.play().then(resolve).catch(err => {
console.warn('Video play was prevented:', err);
resolve(); // Continue even if play was prevented
});
};
if (video.readyState >= 2) { // HAVE_CURRENT_DATA
onLoaded();
} else {
video.addEventListener('loadedmetadata', onLoaded);
}
});
console.log('Camera initialized successfully');
responseText.value = "Camera is ready. Type your question and press Enter.";
return true;
} catch (error) {
console.error("Error initializing camera:", error);
let errorMessage = `Error: ${error.name || 'Unknown error'}`;
if (error.name === 'NotAllowedError') {
errorMessage = "Camera access was denied. Please allow camera access in your browser settings and refresh the page.";
} else if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
errorMessage = "No camera found. Please ensure your camera is properly connected and not in use by another application.";
} else if (error.name === 'NotReadableError') {
errorMessage = "Could not access the camera. It might be in use by another application.";
} else if (error.name === 'OverconstrainedError') {
errorMessage = "Could not start the camera with the requested settings. Please try a different camera.";
} else if (error.message) {
errorMessage = `Error: ${error.message}`;
}
console.error('Camera initialization error:', errorMessage);
responseText.value = errorMessage;
return false;
}
}
// Handle camera selection change
cameraSelect.addEventListener('change', async (e) => {
currentDeviceId = e.target.value;
if (currentDeviceId) {
try {
await initCamera();
responseText.value = `Switched to ${cameraSelect.options[cameraSelect.selectedIndex].text}. Ready to start.`;
} catch (error) {
console.error('Error switching camera:', error);
responseText.value = `Error switching camera: ${error.message || 'Unknown error'}`;
}
}
});
// Handle Enter key in question input
instructionText.addEventListener('keypress', async (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!isProcessing) {
await handleStart();
} else {
await sendData();
}
}
});
// Handle start/stop button click
startButton.addEventListener('click', () => {
if (isProcessing) {
handleStop();
} else {
handleStart();
}
});
async function startCamera() {
try {
responseText.value = "Starting camera...";
// Initialize camera if not already done
if (!video.srcObject) {
const success = await initCamera();
if (!success) return false;
}
isProcessing = true;
startButton.textContent = "Stop";
startButton.classList.remove('start');
startButton.classList.add('stop');
responseText.value = "Camera started. Type your question and press Enter.";
return true;
} catch (error) {
console.error("Error starting camera:", error);
responseText.value = `Error: ${error.message || 'Failed to start camera'}`;
return false;
}
}
function stopCamera() {
if (stream) {
stream.getTracks().forEach(track => track.stop());
video.srcObject = null;
stream = null;
}
isProcessing = false;
startButton.textContent = "Start";
startButton.classList.remove('stop');
startButton.classList.add('start');
}
async function handleStart() {
try {
if (!stream) {
const success = await startCamera();
if (!success) return;
}
isProcessing = true;
startButton.textContent = "Stop";
startButton.classList.remove('start');
startButton.classList.add('stop');
responseText.value = "Camera is active. Type your question and press Enter.";
// Start capturing frames
intervalId = setInterval(sendData, 1000); // Send every second
} catch (error) {
console.error("Error in handleStart:", error);
responseText.value = `Error: ${error.message || 'Failed to start camera'}`;
}
}
async function sendData() {
if (!isProcessing || !stream) return;
try {
// Set canvas size to match video
if (!video.videoWidth || !video.videoHeight) {
console.warn("Video dimensions not ready yet");
return;
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
overlay.width = video.videoWidth;
overlay.height = video.videoHeight;
// Draw current video frame to canvas
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
// Convert canvas to base64
const imageData = canvas.toDataURL('image/jpeg', 0.8);
// Get the instruction text
const instruction = instructionText.value.trim();
if (!instruction) {
responseText.value = "Please enter a question first.";
return;
}
// Show loading state
const currentResponse = responseText.value;
responseText.value = "Processing your request...";
try {
// Send to LM Studio
const response = await sendChatCompletionRequest(instruction, imageData);
responseText.value = response || "No response from AI.";
} catch (error) {
console.error("API Error:", error);
responseText.value = `Error: ${error.message || 'Failed to get response from AI'}`;
// Restore previous response on error
setTimeout(() => { responseText.value = currentResponse; }, 3000);
}
} catch (error) {
console.error("Error in sendData:", error);
responseText.value = `Error: ${error.message || 'Failed to process request'}`;
}
}
function handleStop() {
isProcessing = false;
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
startButton.textContent = "Start";
startButton.classList.remove('stop');
startButton.classList.add('start');
responseText.value = "Camera stopped.";
}
// Initialize when the page loads
window.addEventListener('DOMContentLoaded', async () => {
try {
// First, get the list of available cameras
await getCameras();
// Then initialize the camera if we have a device selected
if (currentDeviceId) {
await initCamera();
}
// Focus the question input
instructionText.focus();
} catch (error) {
console.error('Initialization error:', error);
responseText.value = `Initialization error: ${error.message || 'Unknown error'}`;
}
});
// Stop stream when page is closed/navigated away to release camera
window.addEventListener('beforeunload', () => {
handleStop();
if (stream) {
stream.getTracks().forEach(track => track.stop());
stream = null;
}
});
// Handle window resize to maintain video aspect ratio
window.addEventListener('resize', () => {
if (stream && video.videoWidth && video.videoHeight) {
const container = video.parentElement;
const containerRatio = container.clientWidth / container.clientHeight;
const videoRatio = video.videoWidth / video.videoHeight;
if (containerRatio > videoRatio) {
video.style.width = 'auto';
video.style.height = '100%';
} else {
video.style.width = '100%';
video.style.height = 'auto';
}
}
});
</script>
</body>
</html>