-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
503 lines (419 loc) · 17.9 KB
/
index.html
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
499
500
501
502
503
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Company Side</title>
<style>
#video {
position: fixed;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
object-fit: cover;
}
#take-photo-button {
position: fixed;
bottom: 40px;
left: 50%;
transform: translateX(-50%);
padding: 15px 30px;
background-color: rgba(76, 175, 80, 0.9);
color: white;
border: none;
border-radius: 30px;
cursor: pointer;
font-size: 18px;
z-index: 1000;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
#take-photo-button:hover {
background-color: rgba(62, 142, 65, 0.9);
}
#resultA {
position: fixed;
top: 20px;
right: 20px;
max-width: 200px;
z-index: 1000;
}
#resultA img {
width: 100%;
border: 3px solid white;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
</style>
</head>
<body>
<div class="container">
<h1>Company Side</h1>
<video id="video" autoplay playsinline></video>
<button id="take-photo-button">Take Photo</button>
<div style="display: none;" id="resultA"></div>
<input style="display: none;" type="file" id="imageInput" accept="image/*">
<div>
<canvas id="sourceCanvas"></canvas>
<canvas id="outputCanvas"></canvas>
</div>
<div id="result" class="result"></div>
</div>
<script>
const video = document.getElementById('video');
const takePhotoButton = document.getElementById('take-photo-button');
const resultDiv = document.getElementById('resultA');
let stream = null;
// Request full-screen camera access with highest possible resolution
async function startCamera() {
try {
const constraints = {
video: {
facingMode: 'environment',
}
};
stream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = stream;
} catch (error) {
console.error('Error accessing camera:', error);
alert('Error accessing camera. Please make sure you have given camera permissions.');
}
}
async function takePhoto() {
video.style.display = "none"
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0);
const dataURL = canvas.toDataURL('image/png');
const imageLoadPromise = new Promise((resolve) => {
const image = new Image();
image.onload = () => resolve(image);
image.src = dataURL;
});
// Wait for image to load before proceeding
const img = await imageLoadPromise;
console.log(img);
await main(img);
}
takePhotoButton.addEventListener('click', takePhoto);
startCamera();
</script>
<script>
const GEMINI_API_KEY = [
"AIzaSyAg216xspoLnCCe1Xn8vRsGw7xk-A76wd4",
"AIzaSyBw4eYKGJECwm99vk9pz541Z-ydq0MVZDk",
"AIzaSyBTZU2j_3ebmNLS2ryKugC-t96yC9XtDUg",
];
function getRandomGeminiApiKey() {
const apiKeyIndex = Math.floor(Math.random() * GEMINI_API_KEY.length);
return GEMINI_API_KEY[apiKeyIndex];
}
async function processImage(img, processedBoxes) {
let finishedResponse = [];
for(let i = 0; i < processedBoxes.length; i++) {
finishedResponse.push([]);
}
const sourceCanvas = document.createElement('canvas');
sourceCanvas.width = img.width;
sourceCanvas.height = img.height;
const sourceCtx = sourceCanvas.getContext('2d');
sourceCtx.drawImage(img, 0, 0);
const outputCanvas = document.getElementById('outputCanvas');
outputCanvas.width = img.width;
outputCanvas.height = img.height;
const outputCtx = outputCanvas.getContext('2d');
outputCtx.drawImage(img, 0, 0);
const imageData = sourceCtx.getImageData(0, 0, img.width, img.height);
const width = img.width;
const height = img.height;
// Convert to grayscale
const grayData = new Uint8ClampedArray(width * height);
for (let i = 0; i < imageData.data.length; i += 4) {
const r = imageData.data[i];
const g = imageData.data[i + 1];
const b = imageData.data[i + 2];
grayData[i/4] = 0.299 * r + 0.587 * g + 0.114 * b;
}
// Threshold to binary
const threshold = 128;
const binaryData = new Uint8ClampedArray(width * height);
for (let i = 0; i < grayData.length; i++) {
binaryData[i] = grayData[i] < threshold ? 255 : 0;
}
const visited = new Set();
const objects = [];
// Connected component labeling
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pos = y * width + x;
if (binaryData[pos] === 255 && !visited.has(pos)) {
const object = {
points: [],
bounds: {
minX: x,
maxX: x,
minY: y,
maxY: y
}
};
const stack = [[x, y]];
while (stack.length > 0) {
const [currX, currY] = stack.pop();
const currPos = currY * width + currX;
if (visited.has(currPos)) continue;
visited.add(currPos);
object.points.push([currX, currY]);
object.bounds.minX = Math.min(object.bounds.minX, currX);
object.bounds.maxX = Math.max(object.bounds.maxX, currX);
object.bounds.minY = Math.min(object.bounds.minY, currY);
object.bounds.maxY = Math.max(object.bounds.maxY, currY);
const neighbors = [
[currX + 1, currY],
[currX - 1, currY],
[currX, currY + 1],
[currX, currY - 1]
];
for (const [nextX, nextY] of neighbors) {
if (nextX >= 0 && nextX < width &&
nextY >= 0 && nextY < height) {
const nextPos = nextY * width + nextX;
if (binaryData[nextPos] === 255 && !visited.has(nextPos)) {
stack.push([nextX, nextY]);
}
}
}
}
if (object.points.length > 50) {
objects.push(object);
}
}
}
}
outputCtx.strokeStyle = '#009600';
outputCtx.lineWidth = 5;
function getArea(obj) {
return (obj.bounds.maxX - obj.bounds.minX) * (obj.bounds.maxY - obj.bounds.minY);
}
function isBoundsNear(royce, obj, distance = 10) {
return (
obj.bounds.minX <= royce.xmax + distance &&
obj.bounds.maxX >= royce.xmin - distance &&
obj.bounds.minY <= royce.ymax + distance &&
obj.bounds.maxY >= royce.ymin - distance
);
}
const minArea = 100;
const maxArea = img.width * img.height * 0.3;
objects.forEach((obj) => {
let success = false;
let successInt = 0;
for (let ra = 0; ra < processedBoxes.length; ra++) {
if (isBoundsNear(processedBoxes[ra], obj)) {
success = true;
successInt = ra;
}
}
if (success) {
const area = getArea(obj);
if (area >= minArea && area <= maxArea) {
outputCtx.beginPath();
outputCtx.rect(
obj.bounds.minX,
obj.bounds.minY,
obj.bounds.maxX - obj.bounds.minX,
obj.bounds.maxY - obj.bounds.minY
);
outputCtx.stroke();
let tempCanvas = document.createElement('canvas');
tempCanvas.width = obj.bounds.maxX - obj.bounds.minX;
tempCanvas.height = obj.bounds.maxY - obj.bounds.minY;
let tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(
img,
obj.bounds.minX,
obj.bounds.minY,
obj.bounds.maxX - obj.bounds.minX,
obj.bounds.maxY - obj.bounds.minY,
0,
0,
obj.bounds.maxX - obj.bounds.minX,
obj.bounds.maxY - obj.bounds.minY
);
tempCtx.font = '12px Arial';
tempCtx.fillStyle = 'rgba(255, 255, 255, 1)';
tempCtx.textBaseline = 'top';
tempCtx.textAlign = 'left';
tempCtx.fillText("IMAGE 2", 2, 2);
finishedResponse[successInt].push(tempCanvas.toDataURL('image/png'));
}
}
});
return finishedResponse;
}
function scaleCoordinates(box, imageWidth, imageHeight) {
const normalizedBox = box.map(coord => coord / 1000);
return [
normalizedBox[0] * imageHeight,
normalizedBox[1] * imageWidth,
normalizedBox[2] * imageHeight,
normalizedBox[3] * imageWidth
];
}
async function returnBoxesFromImage(image, boundingBoxes) {
boundingBoxes.forEach((box, index) => {
const [ymin, xmin, ymax, xmax] = scaleCoordinates(box, image.width, image.height);
boundingBoxes[index] = { ymin, xmin, ymax, xmax };
});
return boundingBoxes;
}
async function analyzeImage(base64Image) {
const API_KEY = getRandomGeminiApiKey();
const API_URL = `https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [
{text: "Return a bounding box around each step of the process. [ymin, xmin, ymax, xmax]."},
{inlineData: {data: base64Image, mimeType: "image/png"}}
]
}]
})
});
const data = await response.json();
const text = data.candidates[0].content.parts[0].text;
const regex = /\[(\d+(?:, \d+)*)\]/g;
const matches = text.match(regex);
return matches.map(match => {
return match.slice(1, -1).split(', ').map(Number);
});
}
function displayImages(mainImageBase64, subImageBase64) {
const mainImage = document.createElement('img');
mainImage.src = 'data:image/png;base64,' + mainImageBase64;
const subImage = document.createElement('img');
subImage.src = 'data:image/png;base64,' + subImageBase64;
// Wait for images to load
Promise.all([new Promise((resolve) => {
mainImage.onload = resolve;
}), new Promise((resolve) => {
subImage.onload = resolve;
})]).then(() => {
// Create canvas elements
const mainCanvas = document.createElement('canvas');
const subCanvas = document.createElement('canvas');
// Set canvas dimensions
mainCanvas.width = mainImage.width;
mainCanvas.height = mainImage.height;
subCanvas.width = subImage.width;
subCanvas.height = subImage.height;
// Draw images on canvas
const mainCtx = mainCanvas.getContext('2d');
const subCtx = subCanvas.getContext('2d');
mainCtx.drawImage(mainImage, 0, 0);
subCtx.drawImage(subImage, 0, 0);
// Append canvases to body
document.body.appendChild(mainCanvas);
document.body.appendChild(subCanvas);
});
}
async function analyzeSubImage(step, mainImage, subImage) {
displayImages(mainImage, subImage);
const API_KEY = getRandomGeminiApiKey();
const API_URL = `https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
const responseA = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [
{text: "Is this image an arrow? Return with YES or NO"},
{inlineData: {data: subImage, mimeType: "image/png"}}
]
}]
})
});
const dataA = await responseA.json();
let b = dataA.candidates[0].content.parts[0].text;
if (b.includes("NO")) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [
{text: `We are on step ${step+1}. Is the smaller image in respect to the large image moving UP, DOWN, LEFT, RIGHT, or NOT MOVING.`},
{inlineData: {data: mainImage, mimeType: "image/png"}},
{inlineData: {data: subImage, mimeType: "image/png"}}
]
}]
})
});
const data = await response.json();
return data.candidates[0].content.parts[0].text;
}
}
async function main(img) {
console.log(img.width);
// Display source image
const sourceCanvas = document.getElementById('sourceCanvas');
sourceCanvas.width = img.width;
sourceCanvas.height = img.height;
const sourceCtx = sourceCanvas.getContext('2d');
sourceCtx.drawImage(img, 0, 0);
const tempCanvas = document.createElement('canvas');
tempCanvas.width = img.width;
tempCanvas.height = img.height;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(img, 0, 0);
const base64Image = tempCanvas.toDataURL('image/png').split(',')[1];
let boundingBoxes, processedBoxes;
let retries = 0;
const maxRetries = 5;
let success = false;
while (!success && retries < maxRetries) {
try {
boundingBoxes = await analyzeImage(base64Image);
processedBoxes = await returnBoxesFromImage(img, boundingBoxes);
success = true;
} catch (error) {
retries++;
console.error(`Error occurred, retrying (${retries}/${maxRetries}):`, error);
await new Promise(resolve => setTimeout(resolve, 100));
}
}
if (!success) {
console.error(`Failed to retrieve bounding boxes after ${maxRetries} retries.`);
return;
}
const output = await processImage(img, processedBoxes);
let step = 0;
let curr_obj = 0;
alert(output[0].length)
alert(output[1].length)
alert(output.length)
const result = await analyzeSubImage(step, base64Image, output[step][curr_obj].split(',')[1]);
document.getElementById('result').textContent = result;
alert(result);
}
document.getElementById('imageInput').addEventListener('change', async (e) => {
const file = e.target.files[0];
const img = new Image();
img.src = URL.createObjectURL(file);
await new Promise(resolve => img.onload = resolve);
await main(img);
});
</script>
</body>
</html>