ashvardanian
commited on
Commit
•
0b5daf1
1
Parent(s):
5d1f533
Upload 3 files
Browse files- images.zip +3 -0
- main.py +57 -0
- requirements.txt +6 -0
images.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb6a68e6bace132ee827d922adb88554da67d5a7806cf0ca9e39545aa924abc2
|
3 |
+
size 406969617
|
main.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from os import listdir, path, PathLike
|
2 |
+
from os.path import isfile, join
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image
|
7 |
+
from PIL import ImageFile
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
from uform import get_model
|
11 |
+
from usearch.index import Index
|
12 |
+
from usearch.io import save_matrix, load_matrix
|
13 |
+
|
14 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
15 |
+
|
16 |
+
|
17 |
+
def is_image(path: PathLike) -> bool:
|
18 |
+
if not isfile(path):
|
19 |
+
return False
|
20 |
+
try:
|
21 |
+
Image.open(path)
|
22 |
+
return True
|
23 |
+
except:
|
24 |
+
return False
|
25 |
+
|
26 |
+
|
27 |
+
names = sorted(f for f in listdir('images') if is_image(join('images', f)))
|
28 |
+
|
29 |
+
names = [filename.rsplit('.', 1)[0] for filename in names]
|
30 |
+
table = pd.read_table('images.tsv') if path.exists(
|
31 |
+
'images.tsv') else pd.read_table('images.csv')
|
32 |
+
table = table[table['photo_id'].isin(names)]
|
33 |
+
table = table.sort_values('photo_id')
|
34 |
+
table.reset_index()
|
35 |
+
table.to_csv('images.csv', index=False)
|
36 |
+
|
37 |
+
names = list(set(table['photo_id']).intersection(names))
|
38 |
+
|
39 |
+
model = get_model('unum-cloud/uform-vl-english')
|
40 |
+
vectors = []
|
41 |
+
|
42 |
+
for name in tqdm(names, desc='Vectorizing images'):
|
43 |
+
image = Image.open(join('images', name + '.jpg'))
|
44 |
+
image_data = model.preprocess_image(image)
|
45 |
+
image_embedding = model.encode_image(image_data).detach().numpy()
|
46 |
+
vectors.append(image_embedding)
|
47 |
+
|
48 |
+
image_mat = np.concatenate(vectors)
|
49 |
+
save_matrix(image_mat, 'images.fbin')
|
50 |
+
|
51 |
+
index = Index(ndim=256, metric='cos')
|
52 |
+
image_mat = load_matrix('images.fbin')
|
53 |
+
|
54 |
+
for idx, vector in tqdm(enumerate(vectors), desc='Indexing vectors'):
|
55 |
+
index.add(idx, vector.flatten())
|
56 |
+
|
57 |
+
index.save('images.usearch')
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
uform
|
2 |
+
usearch
|
3 |
+
|
4 |
+
numpy
|
5 |
+
Pillow
|
6 |
+
tqdm
|