Views
No views yet
npm i @xenova/transformers1import { AutoModel, AutoProcessor, RawImage, Tensor, dot, softmax } from '@xenova/transformers';
2
3// Load vision and location models
4const model_id = 'Xenova/geoclip-large-patch14';
5const vision_model = await AutoModel.from_pretrained(model_id, {
6 model_file_name: 'vision_model',
7});
8const location_model = await AutoModel.from_pretrained(model_id, {
9 model_file_name: 'location_model',
10 quantized: false,
11});
12
13// Load image processor
14const processor = await AutoProcessor.from_pretrained('openai/clip-vit-large-patch14');
15
16// Read and preprocess image
17const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/moraine-lake.png';
18const image = await RawImage.fromURL(url);
19const vision_inputs = await processor(image);
20
21// Compute image embeddings
22const { image_embeds } = await vision_model(vision_inputs);
23const norm_image_embeds = image_embeds.normalize().data;
24
25// Define a list of candidate GPS coordinates
26// https://github.com/VicenteVivan/geo-clip/blob/main/geoclip/model/gps_gallery/coordinates_100K.csv
27const coordinate_data = 'https://huggingface.co/Xenova/geoclip-large-patch14/resolve/main/gps_gallery/coordinates_100K.json';
28const gps_data = await (await fetch(coordinate_data)).json();
29
30// Compute location embeddings and compare to image embeddings
31const coordinate_batch_size = 512;
32const exp_logit_scale = Math.exp(3.681034803390503); // Used for scaling logits
33const scores = [];
34for (let i = 0; i < gps_data.length; i += coordinate_batch_size) {
35 const chunk = gps_data.slice(i, i + coordinate_batch_size);
36
37 const { location_embeds } = await location_model({
38 location: new Tensor('float32', chunk.flat(), [chunk.length, 2])
39 });
40
41 const norm_location_embeds = location_embeds.normalize().tolist();
42 for (const embed of norm_location_embeds) {
43 const score = exp_logit_scale * dot(norm_image_embeds, embed);
44 scores.push(score);
45 }
46}
47
48// Get top predictions
49const top_k = 50;
50const results = softmax(scores)
51 .map((x, i) => [x, i])
52 .sort((a, b) => b[0] - a[0])
53 .slice(0, top_k)
54 .map(([score, index]) => ({ index, gps: gps_data[index], score }));
55
56console.log('=======================');
57console.log('Top 5 GPS Predictions 📍');
58console.log('=======================');
59for (let i = 0; i < 5; ++i) {
60 console.log(results[i]);
61}
62console.log('=======================');=======================
Top 5 GPS Predictions 📍
=======================
{
index: 75129,
gps: [ 51.327447, -116.183509 ],
score: 0.06895832493631944
}
{
index: 5158,
gps: [ 51.326401, -116.18263 ],
score: 0.06843383108770337
}
{
index: 77752,
gps: [ 51.328198, -116.180934 ],
score: 0.06652924543010541
}
{
index: 32529,
gps: [ 51.327809, -116.180334 ],
score: 0.065981075526145
}
{
index: 461,
gps: [ 51.322353, -116.18557 ],
score: 0.06476605375767822
}
=======================
onnx).