Ashot Vardanian commited on
Commit
e01653e
1 Parent(s): 95669d7

Fix: Vectorizing images and indexing on-demand

Browse files
Files changed (1) hide show
  1. main.py +20 -17
main.py CHANGED
@@ -1,6 +1,6 @@
1
  #!/usr/bin/env python3
2
  from os import listdir, path, PathLike, remove
3
- from os.path import isfile, join
4
 
5
  import pandas as pd
6
  import numpy as np
@@ -9,7 +9,7 @@ from PIL import ImageFile
9
  from tqdm import tqdm
10
 
11
  from uform import get_model
12
- from usearch.index import Index
13
  from usearch.io import save_matrix, load_matrix
14
 
15
  ImageFile.LOAD_TRUNCATED_IMAGES = True
@@ -21,7 +21,7 @@ def is_image(path: PathLike) -> bool:
21
  try:
22
  Image.open(path)
23
  return True
24
- except:
25
  return False
26
 
27
 
@@ -48,22 +48,25 @@ if len(names_to_delete) > 0:
48
  for name in names_to_delete:
49
  remove(join('images', name))
50
 
51
- model = get_model('unum-cloud/uform-vl-english')
52
- vectors = []
 
53
 
54
- for name in tqdm(names, desc='Vectorizing images'):
55
- image = Image.open(join('images', name + '.jpg'))
56
- image_data = model.preprocess_image(image)
57
- image_embedding = model.encode_image(image_data).detach().numpy()
58
- vectors.append(image_embedding)
59
 
60
- image_mat = np.concatenate(vectors)
61
- save_matrix(image_mat, 'images.fbin')
62
 
63
- index = Index(ndim=256, metric='cos')
64
- image_mat = load_matrix('images.fbin')
 
 
65
 
66
- for idx, vector in tqdm(enumerate(vectors), desc='Indexing vectors'):
67
- index.add(idx, vector.flatten())
68
 
69
- index.save('images.usearch')
 
1
  #!/usr/bin/env python3
2
  from os import listdir, path, PathLike, remove
3
+ from os.path import isfile, join, exists
4
 
5
  import pandas as pd
6
  import numpy as np
 
9
  from tqdm import tqdm
10
 
11
  from uform import get_model
12
+ from usearch.index import Index, MetricKind
13
  from usearch.io import save_matrix, load_matrix
14
 
15
  ImageFile.LOAD_TRUNCATED_IMAGES = True
 
21
  try:
22
  Image.open(path)
23
  return True
24
+ except Exception:
25
  return False
26
 
27
 
 
48
  for name in names_to_delete:
49
  remove(join('images', name))
50
 
51
+ if not exists('images.fbin'):
52
+ model = get_model('unum-cloud/uform-vl-english')
53
+ vectors = []
54
 
55
+ for name in tqdm(names, desc='Vectorizing images'):
56
+ image = Image.open(join('images', name + '.jpg'))
57
+ image_data = model.preprocess_image(image)
58
+ image_embedding = model.encode_image(image_data).detach().numpy()
59
+ vectors.append(image_embedding)
60
 
61
+ image_mat = np.concatenate(vectors)
62
+ save_matrix(image_mat, 'images.fbin')
63
 
64
+ if not exists('images.usearch'):
65
+ index = Index(ndim=256, metric=MetricKind.Cos)
66
+ image_mat = load_matrix('images.fbin')
67
+ count = image_mat.shape[0]
68
 
69
+ for idx in tqdm(range(count), desc='Indexing vectors'):
70
+ index.add(idx, image_mat[idx, :].flatten())
71
 
72
+ index.save('images.usearch')