Fix: Embeddings file ordering

#1
by VoVoR - opened
Files changed (2) hide show
  1. images.fbin +1 -1
  2. main.py +212 -51
images.fbin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:16f635d1f477649283707e704c32dc1d54b7a4e3ae560b6da7c0330bd655ee1e
3
  size 24875016
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e673d5acf7f4a30f67b91d2cd3fcec73ed9b8891c61c22a3e4cda053ba8c7b6
3
  size 24875016
main.py CHANGED
@@ -1,72 +1,233 @@
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
7
- from PIL import Image
8
- from PIL import ImageFile
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
16
 
 
17
 
18
- def is_image(path: PathLike) -> bool:
19
- if not isfile(path):
20
- return False
21
- try:
22
- Image.open(path)
23
- return True
24
- except Exception:
25
- return False
26
 
 
 
27
 
28
- def trim_extension(filename: str) -> str:
29
- return filename.rsplit('.', 1)[0]
30
 
 
 
 
 
31
 
32
- names = sorted(f for f in listdir('images') if is_image(join('images', f)))
33
- names = [trim_extension(f) for f in names]
34
 
35
- table = pd.read_table('images.tsv') if path.exists(
36
- 'images.tsv') else pd.read_table('images.csv')
37
- table = table[table['photo_id'].isin(names)]
38
- table = table.sort_values('photo_id')
39
- table.reset_index()
40
- table.to_csv('images.csv', index=False)
41
 
42
- names = list(set(table['photo_id']).intersection(names))
43
- names_to_delete = [f for f in listdir(
44
- 'images') if trim_extension(f) not in names]
45
 
46
- if len(names_to_delete) > 0:
47
- print(f'Plans to delete: {len(names_to_delete)} images without metadata')
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')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import base64
4
+ import mimetypes
5
 
 
6
  import numpy as np
7
+ import streamlit as st
8
+ import pandas as pd
9
+ import altair as alt
10
+ import sklearn as skl
11
+ import PIL as pil
12
 
13
  from uform import get_model
14
  from usearch.index import Index, MetricKind
 
15
 
16
+ # Managing data
17
 
18
+ script_path: str = os.path.dirname(os.path.abspath(__file__))
19
 
20
+ data_path: str = os.environ.get(
21
+ 'UNSPLASH_SEARCH_PATH', os.path.join(script_path, 'dataset'))
 
 
 
 
 
 
22
 
23
+ view_local_images: bool = True if os.environ.get(
24
+ 'STREAMLIT_SERVER_ENABLE_STATIC_SERVING') else False
25
 
 
 
26
 
27
+ image_query = bytes()
28
+ text_query = str()
29
+ results = list()
30
+ max_caption_length: int = 100
31
 
 
 
32
 
33
+ class FileNotFoundError(Exception):
34
+ pass
 
 
 
 
35
 
 
 
 
36
 
37
+ def img_to_data(path):
38
+ """Convert a file (specified by a path) into a data URI."""
39
+ if not os.path.exists(path):
40
+ raise FileNotFoundError
41
+ mime, _ = mimetypes.guess_type(path)
42
+ with open(path, 'rb') as fp:
43
+ data = fp.read()
44
+ data64 = base64.b64encode(data).decode('utf-8')
45
+ return f'data:{mime}/jpg;base64,{data64}'
46
 
 
 
 
47
 
48
+ @st.cache_resource
49
+ def get_uform_model():
50
+ return get_model('unum-cloud/uform-vl-english')
 
 
51
 
 
 
52
 
53
+ @st.cache_resource
54
+ def get_unsplash_metadata():
55
+ path = os.path.join(data_path, 'images.csv')
56
+ assert os.path.exists(path), 'Missing metadata file'
57
+ df = pd.read_csv(path, dtype=str).fillna('')
58
+ df['photo_submitted_at'] = pd.to_datetime(
59
+ df['photo_submitted_at'], format='mixed')
60
+ return df
61
 
 
 
62
 
63
+ @st.cache_resource
64
+ def get_unsplash_usearch_index():
65
+ index = Index(ndim=256, metric=MetricKind.Cos)
66
+ path = os.path.join(data_path, 'images.usearch')
67
+ assert os.path.exists(path), 'Missing index file'
68
+ index.view(path)
69
+ return index
70
+
71
+
72
+ # GUI setup
73
+
74
+ st.set_page_config(
75
+ page_title='USearch through Unsplash',
76
+ page_icon='🐍', layout='wide',
77
+ initial_sidebar_state='collapsed',
78
+ )
79
+
80
+ st.title('USearch through Unsplash')
81
+
82
+
83
+ text_query: str = st.text_input(
84
+ 'Search Bar',
85
+ placeholder='Search for Unsplash photos',
86
+ value='', key='text_query',
87
+ label_visibility='collapsed')
88
+ if not len(text_query):
89
+ text_query = None
90
+
91
+ image_query: io.BytesIO = st.file_uploader(
92
+ 'Alternatively, choose an image file')
93
+
94
+ layout: str = st.radio(
95
+ 'Layout',
96
+ ('List', 'Grid', 'Semantics'),
97
+ horizontal=True,
98
+ label_visibility='collapsed')
99
+
100
+ columns: int = st.sidebar.slider(
101
+ 'Grid Columns', min_value=1, max_value=10, value=5)
102
+ show_captions: bool = st.sidebar.checkbox('Show Captions in Grid', value=True)
103
+ max_results: int = st.sidebar.number_input(
104
+ 'Max Matches', min_value=1, max_value=None, value=100)
105
+
106
+ model = get_uform_model()
107
+ table = get_unsplash_metadata()
108
+ index = get_unsplash_usearch_index()
109
+
110
+ # Search Content
111
+
112
+ if not text_query and not image_query:
113
+ results = table[:max_results]
114
+
115
+ else:
116
+ with st.spinner(f'We are searching through {len(table)} entries'):
117
+
118
+ if image_query:
119
+ image_query = pil.Image.open(image_query)
120
+ query_data = model.preprocess_image(image_query)
121
+ query_embedding = model.encode_image(query_data).detach().numpy()
122
+ else:
123
+ query_data = model.preprocess_text(text_query)
124
+ query_embedding = model.encode_text(query_data).detach().numpy()
125
+
126
+ # We don't need the text-based search, if we have AI :)
127
+ # results = table[table['photo_description'].str.contains(
128
+ # text_query)][:max_results]
129
+ matches, _, _ = index.search(
130
+ query_embedding.flatten(),
131
+ max_results,
132
+ exact=True,
133
+ )
134
+ results = table.iloc[matches]
135
+
136
+ st.success(
137
+ f'Found {len(results)} matches among {len(table)} entries!', icon='✅')
138
+
139
+
140
+ # Join metadata with images
141
+
142
+ results = results.copy().reset_index()
143
+ results['photo_image_base64'] = [
144
+ img_to_data(os.path.join(data_path, 'images', id + '.jpg'))
145
+ for id in results['photo_id']]
146
+
147
+
148
+ # Visualize Matches
149
+
150
+ if layout == 'List':
151
+
152
+ columns = [
153
+ 'photo_image_base64',
154
+ 'photo_description',
155
+ 'ai_description',
156
+ 'photographer_username',
157
+ 'photo_submitted_at',
158
+ 'stats_views',
159
+ 'stats_downloads',
160
+ 'photo_id',
161
+ 'photo_url',
162
+ 'photo_image_url',
163
+ ]
164
+ visible_results = results[columns]
165
+
166
+ st.dataframe(
167
+ visible_results,
168
+ column_config={
169
+ 'photo_id': st.column_config.TextColumn('ID'),
170
+ 'photo_url': st.column_config.LinkColumn('Page'),
171
+ 'photo_image_url': st.column_config.LinkColumn('Remote'),
172
+ 'photo_image_base64': st.column_config.ImageColumn(
173
+ 'Local',
174
+ width='large'),
175
+ 'photo_submitted_at': st.column_config.DatetimeColumn(
176
+ 'Time',
177
+ format='DD.MM.YYYY',
178
+ ),
179
+ 'photo_description': st.column_config.TextColumn('Human Text'),
180
+ 'ai_description': st.column_config.TextColumn('AI Text'),
181
+ 'photographer_username': st.column_config.TextColumn('Author'),
182
+ 'stats_views': st.column_config.NumberColumn('Views'),
183
+ 'stats_downloads': st.column_config.NumberColumn('Downloads'),
184
+ },
185
+ use_container_width=True,
186
+ hide_index=False,
187
+ height=1000,
188
+ )
189
+
190
+ elif layout == 'Semantics':
191
+
192
+ vectors = np.vstack([
193
+ index.reconstruct(id, dtype=np.float32)
194
+ for id in results['photo_id']])
195
+
196
+ tsne = skl.manifold.TSNE(
197
+ n_components=2, learning_rate='auto',
198
+ init='random', perplexity=3).fit_transform(vectors)
199
+
200
+ results['x'] = tsne[:, 0]
201
+ results['y'] = tsne[:, 1]
202
+
203
+ altair_chart = alt.Chart(results).mark_circle(size=200).encode(
204
+ x='x',
205
+ y='y',
206
+ tooltip=['photo_image_base64'],
207
+ )
208
+ st.altair_chart(altair_chart, use_container_width=True, theme='streamlit')
209
+
210
+ elif layout == 'Grid':
211
+
212
+ for n_row, row in results.reset_index().iterrows():
213
+ i = n_row % columns
214
+ if i == 0:
215
+ st.write('---')
216
+ cols = st.columns(columns, gap='large')
217
+
218
+ with cols[n_row % columns]:
219
+ id = row['photo_id']
220
+ username = row['photographer_username'].strip()
221
+ preview_path = row['photo_image_base64']
222
+
223
+ if show_captions:
224
+ description = row['photo_description'].strip()
225
+ if len(description) > max_caption_length:
226
+ description = description[:max_caption_length] + '...'
227
+ description = f'{description} \@{username}'
228
+ else:
229
+ description = ''
230
+ st.image(
231
+ preview_path,
232
+ caption=description,
233
+ use_column_width='always')