-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
gemini-bbox.html
334 lines (292 loc) · 13 KB
/
gemini-bbox.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gemini API Image Bounding Box Visualization</title>
<script type="module">
import { GoogleGenerativeAI } from "https://esm.run/@google/generative-ai";
import { marked } from "https://esm.run/marked";
function getApiKey() {
let apiKey = localStorage.getItem("GEMINI_API_KEY");
if (!apiKey) {
apiKey = prompt("Please enter your Gemini API key:");
if (apiKey) {
localStorage.setItem("GEMINI_API_KEY", apiKey);
}
}
return apiKey;
}
async function getGenerativeModel(params) {
const API_KEY = getApiKey();
const genAI = new GoogleGenerativeAI(API_KEY);
return genAI.getGenerativeModel(params);
}
async function fileToGenerativePart(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve({
inlineData: {
data: reader.result.split(",")[1],
mimeType: file.type
}
});
reader.readAsDataURL(file);
});
}
function resizeAndCompressImage(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
if (width > 1000) {
height = Math.round((height * 1000) / width);
width = 1000;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(new File([blob], "compressed_image.jpg", { type: "image/jpeg" }));
}, 'image/jpeg', 0.7);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
}
async function processImageAndPrompt() {
const fileInput = document.getElementById('imageInput');
const promptInput = document.getElementById('promptInput');
const resultDiv = document.getElementById('result');
const modelSelect = document.getElementById('modelSelect');
if (!promptInput.value) {
alert('Please enter a prompt.');
return;
}
resultDiv.innerHTML = 'Processing...';
// Clear previous bounding box images
document.getElementById('boundingBoxImages').innerHTML = '';
try {
const model = await getGenerativeModel({ model: modelSelect.value });
let content = [promptInput.value];
if (fileInput.files[0]) {
const compressedImage = await resizeAndCompressImage(fileInput.files[0]);
const imagePart = await fileToGenerativePart(compressedImage);
content.push(imagePart);
}
const result = await model.generateContent(content);
const response = await result.response;
const text = response.text();
resultDiv.innerHTML = marked.parse(text);
if (fileInput.files[0]) {
// Extract coordinates from the response
const coordinates = extractCoordinates(text);
if (coordinates.length > 0) {
displayImageWithBoundingBoxes(fileInput.files[0], coordinates);
}
}
} catch (error) {
resultDiv.innerHTML = `Error: ${error.message}`;
}
}
function extractCoordinates(text) {
const regex = /\[\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\]/g;
const matches = text.match(regex) || [];
return matches.map(JSON.parse);
}
function displayImageWithBoundingBoxes(file, coordinates) {
const reader = new FileReader();
reader.onload = function(event) {
const image = new Image();
image.onload = function() {
const canvas = document.getElementById('canvas');
canvas.width = image.width + 100;
canvas.height = image.height + 100;
const ctx = canvas.getContext('2d');
// Draw the image
ctx.drawImage(image, 80, 20);
// Draw grid lines
ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'; // Red with 50% opacity
ctx.lineWidth = 1;
// Vertical grid lines
for (let i = 0; i <= 1000; i += 100) {
const x = 80 + i / 1000 * image.width;
ctx.beginPath();
ctx.moveTo(x, 20);
ctx.lineTo(x, image.height + 20);
ctx.stroke();
}
// Horizontal grid lines
for (let i = 0; i <= 1000; i += 100) {
const y = 20 + (1000 - i) / 1000 * image.height;
ctx.beginPath();
ctx.moveTo(80, y);
ctx.lineTo(image.width + 80, y);
ctx.stroke();
}
// Draw bounding boxes
const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
const boundingBoxImages = document.getElementById('boundingBoxImages');
boundingBoxImages.innerHTML = ''; // Clear previous bounding box images
coordinates.forEach((box, index) => {
const [ymin, xmin, ymax, xmax] = box.map(coord => coord / 1000);
const width = (xmax - xmin) * image.width;
const height = (ymax - ymin) * image.height;
ctx.strokeStyle = colors[index % colors.length];
ctx.lineWidth = 5;
ctx.strokeRect(xmin * image.width + 80, ymin * image.height + 20, width, height);
// Extract bounding box image
const boundingBoxCanvas = document.createElement('canvas');
boundingBoxCanvas.width = width;
boundingBoxCanvas.height = height;
const bbCtx = boundingBoxCanvas.getContext('2d');
bbCtx.drawImage(image, xmin * image.width, ymin * image.height, width, height, 0, 0, width, height);
// Convert canvas to JPEG base64 data URI
const dataURI = boundingBoxCanvas.toDataURL('image/jpeg');
const boundingBoxContainer = document.createElement('div');
boundingBoxContainer.className = 'bounding-box-container';
const title = document.createElement('p');
title.textContent = `Bounding Box: [${box.join(', ')}]`;
boundingBoxContainer.appendChild(title);
const img = document.createElement('img');
img.src = dataURI;
img.style.width = `${Math.round(width)}px`;
img.style.height = `${Math.round(height)}px`;
boundingBoxContainer.appendChild(img);
boundingBoxImages.appendChild(boundingBoxContainer);
});
// Draw axes and labels
ctx.strokeStyle = '#000000';
ctx.lineWidth = 1;
ctx.font = '26px Arial';
ctx.textAlign = 'right';
// Y-axis
ctx.beginPath();
ctx.moveTo(80, 20);
ctx.lineTo(80, image.height + 20);
ctx.stroke();
// Y-axis labels and ticks
for (let i = 0; i <= 1000; i += 100) {
const y = 20 + i / 1000 * image.height;
ctx.fillText(i.toString(), 75, y + 5);
ctx.beginPath();
ctx.moveTo(75, y);
ctx.lineTo(80, y);
ctx.stroke();
}
// X-axis
ctx.beginPath();
ctx.moveTo(80, image.height + 20);
ctx.lineTo(image.width + 80, image.height + 20);
ctx.stroke();
// X-axis labels and ticks
ctx.textAlign = 'center';
for (let i = 0; i <= 1000; i += 100) {
const x = 80 + i / 1000 * image.width;
ctx.fillText(i.toString(), x, image.height + 40);
ctx.beginPath();
ctx.moveTo(x, image.height + 20);
ctx.lineTo(x, image.height + 25);
ctx.stroke();
}
};
image.src = event.target.result;
};
reader.readAsDataURL(file);
}
function clearImage() {
document.getElementById('imageInput').value = '';
document.getElementById('canvas').getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('imagePreview').src = '';
document.getElementById('imagePreview').style.display = 'none';
document.getElementById('boundingBoxImages').innerHTML = '';
}
function previewImage(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById('imagePreview');
img.src = e.target.result;
img.style.display = 'block';
}
reader.readAsDataURL(file);
}
}
// Attach event listeners
document.getElementById('submitBtn').addEventListener('click', processImageAndPrompt);
document.getElementById('clearImageBtn').addEventListener('click', clearImage);
document.getElementById('imageInput').addEventListener('change', previewImage);
</script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
textarea {
width: 100%;
height: 100px;
}
#result, #imageContainer {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
#canvas {
max-width: 100%;
height: auto;
}
#imagePreview {
max-width: 100%;
display: none;
margin-top: 10px;
}
#boundingBoxImages {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin-top: 20px;
}
.bounding-box-container {
display: block;
margin-bottom: 20px;
}
.bounding-box-container p {
margin: 0 0 5px 0;
font-weight: bold;
}
.bounding-box-container img {
display: block;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h1>Gemini API Image Bounding Box Visualization</h1>
<select id="modelSelect">
<option value="gemini-2.0-flash-exp">gemini-2.0-flash-exp</option>
<option value="gemini-1.5-pro-latest">gemini-1.5-pro</option>
<option value="gemini-1.5-flash-latest">gemini-1.5-flash</option>
<option value="gemini-1.5-flash-8b-latest">gemini-1.5-flash-8b</option>
</select>
<input type="file" id="imageInput" accept="image/*">
<button id="clearImageBtn">Clear Image</button>
<textarea id="promptInput">Return bounding boxes as JSON arrays [ymin, xmin, ymax, xmax]
</textarea>
<button id="submitBtn">Process</button>
<div id="result"></div>
<div id="imageContainer">
<img id="imagePreview" alt="Image preview" />
<canvas id="canvas"></canvas>
</div>
<div id="boundingBoxImages"></div>
</body>
</html>