-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage-embeddings-tensorflow.js
More file actions
61 lines (52 loc) · 2.11 KB
/
image-embeddings-tensorflow.js
File metadata and controls
61 lines (52 loc) · 2.11 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
function calculateImageEmbeddings() {
return new Promise(async (resolve, reject) => {
try {
// Load TensorFlow.js
await new Promise((res, rej) => {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.11.0';
script.onload = res;
script.onerror = rej;
document.head.appendChild(script);
});
// Load MobileNet model
await new Promise((res, rej) => {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.0';
script.onload = res;
script.onerror = rej;
document.head.appendChild(script);
});
// Ensure TensorFlow.js is ready
await tf.ready();
const img = document.querySelector('img');
if (!img) {
throw new Error('No image found on the page');
}
await new Promise((res) => {
if (img.complete) res();
else img.onload = res;
});
const model = await mobilenet.load();
const tensor = tf.browser.fromPixels(img)
.resizeBilinear([224, 224])
.toFloat()
.div(tf.scalar(127.5))
.sub(tf.scalar(1))
.expandDims(0);
const embeddings = model.infer(tensor, true);
// Normalize embeddings to avoid zeros
const normalizedEmbeddings = tf.tidy(() => {
const mean = tf.mean(embeddings);
const std = tf.moments(embeddings).variance.sqrt();
return embeddings.sub(mean).div(std);
});
resolve(Array.from(normalizedEmbeddings.dataSync()).toString());
} catch (error) {
reject(error);
}
});
}
return calculateImageEmbeddings()
.then(embeddings => seoSpider.data(embeddings))
.catch(error => seoSpider.error(error.toString()));