JavierFnts commited on
Commit
30c8dd0
β€’
1 Parent(s): fe3ce1c

Refactored to use local clip

Browse files
Files changed (3) hide show
  1. clip_model.py +61 -0
  2. requirements.txt +1 -1
  3. streamlit_app.py +49 -65
clip_model.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import clip
2
+ from PIL.Image import Image
3
+ import torch
4
+
5
+ class ClipModel:
6
+ def __init__(self, model_name: str = 'RN50') -> None:
7
+ """
8
+ Available models
9
+ ['RN50', 'RN101', 'RN50x4', 'RN50x16', 'RN50x64', 'ViT-B/32',
10
+ 'ViT-B/16', 'ViT-L/14', 'ViT-L/14@336px']
11
+ """
12
+ self.model, self.img_preprocess = clip.load(model_name)
13
+
14
+ def predict(self, images: list[Image], prompts: list[str]) -> dict:
15
+ if len(images) == 1:
16
+ return self.compute_prompts_probabilities(images[0], prompts)
17
+ elif len(prompts) == 1:
18
+ return self.compute_images_probabilities(images, prompts[0])
19
+ else:
20
+ raise ValueError('Either images or prompts must be a single element')
21
+
22
+ def compute_prompts_probabilities(self, image: Image, prompts: list[str]) -> dict[str, float]:
23
+ preprocessed_image = self.img_preprocess(image).unsqueeze(0)
24
+ tokenized_prompts = clip.tokenize(prompts)
25
+ with torch.inference_mode():
26
+ image_features = self.model.encode_image(preprocessed_image)
27
+ text_features = self.model.encode_text(tokenized_prompts)
28
+
29
+ # normalized features
30
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
31
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
32
+
33
+ # cosine similarity as logits
34
+ logit_scale = self.model.logit_scale.exp()
35
+ logits_per_image = logit_scale * image_features @ text_features.t()
36
+
37
+ probs = list(logits_per_image.softmax(dim=-1).cpu().numpy()[0])
38
+
39
+ scored_prompts = {tag: float(prob) for tag, prob in zip(prompts, probs)}
40
+ return scored_prompts
41
+
42
+ def compute_images_probabilities(self, images: list[Image], prompt: str) -> dict[Image, float]:
43
+ raise
44
+ preprocessed_images = [self.img_preprocess(image).unsqueeze(0) for image in images]
45
+ tokenized_prompts = clip.tokenize(prompt)
46
+ with torch.inference_mode():
47
+ image_features = self.model.encode_image(preprocessed_image)
48
+ text_features = self.model.encode_text(tokenized_prompts)
49
+
50
+ # normalized features
51
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
52
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
53
+
54
+ # cosine similarity as logits
55
+ logit_scale = self.model.logit_scale.exp()
56
+ logits_per_image = logit_scale * image_features @ text_features.t()
57
+
58
+ probs = list(logits_per_image.softmax(dim=-1).cpu().numpy()[0])
59
+
60
+ scored_prompts = {tag: float(prob) for tag, prob in zip(prompts, probs)}
61
+ return scored_prompts
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
  streamlit~=0.76.0
2
- booste==0.2.8
3
  Pillow==8.1.0
4
  mock==4.0.3
 
1
  streamlit~=0.76.0
2
+ git+https://github.com/openai/CLIP@b46f5ac
3
  Pillow==8.1.0
4
  mock==4.0.3
streamlit_app.py CHANGED
@@ -1,40 +1,36 @@
1
  import random
 
2
 
3
  import streamlit as st
 
4
 
5
  from session_state import SessionState, get_state
6
  from images_mocker import ImagesMocker
7
 
8
- images_mocker = ImagesMocker()
9
- import booste
10
-
11
  from PIL import Image
12
 
13
- # Unfortunately Streamlit sharing does not allow to hide enviroment variables yet.
14
- # Do not copy this API key, go to https://www.booste.io/ and get your own, it is free!
15
- BOOSTE_API_KEY = "3818ba84-3526-4029-9dc8-ef3038697ea2"
16
-
17
  IMAGES_LINKS = ["https://cdn.pixabay.com/photo/2014/10/13/21/34/clipper-487503_960_720.jpg",
18
  "https://cdn.pixabay.com/photo/2019/09/06/04/25/beach-4455433_960_720.jpg",
19
- # "https://cdn.pixabay.com/photo/2019/10/19/12/21/hot-air-balloons-4561264_960_720.jpg",
20
- # "https://cdn.pixabay.com/photo/2019/12/17/18/20/peacock-4702197_960_720.jpg",
21
- # "https://cdn.pixabay.com/photo/2016/11/15/16/24/banana-1826760_960_720.jpg",
22
- # "https://cdn.pixabay.com/photo/2020/12/28/22/48/buddha-5868759_960_720.jpg",
23
  "https://cdn.pixabay.com/photo/2019/11/11/14/30/zebra-4618513_960_720.jpg",
24
  "https://cdn.pixabay.com/photo/2020/11/04/15/29/coffee-beans-5712780_960_720.jpg",
25
  "https://cdn.pixabay.com/photo/2020/03/24/20/42/namibia-4965457_960_720.jpg",
26
  "https://cdn.pixabay.com/photo/2020/08/27/07/31/restaurant-5521372_960_720.jpg",
27
- # "https://cdn.pixabay.com/photo/2020/08/28/06/13/building-5523630_960_720.jpg",
28
  "https://cdn.pixabay.com/photo/2020/08/24/21/41/couple-5515141_960_720.jpg",
29
  "https://cdn.pixabay.com/photo/2020/01/31/07/10/billboards-4807268_960_720.jpg",
30
  "https://cdn.pixabay.com/photo/2017/07/31/20/48/shell-2560930_960_720.jpg",
31
  "https://cdn.pixabay.com/photo/2020/08/13/01/29/koala-5483931_960_720.jpg",
32
- # "https://cdn.pixabay.com/photo/2016/11/29/04/52/architecture-1867411_960_720.jpg",
33
  ]
34
 
35
  @st.cache # Cache this so that it doesn't change every time something changes in the page
36
- def select_random_dataset():
37
- return random.sample(IMAGES_LINKS, 10)
 
 
 
 
 
 
 
38
 
39
 
40
  def limit_number_images(state: SessionState):
@@ -140,19 +136,19 @@ class Sections:
140
  def image_picker(state: SessionState, default_text_input: str):
141
  col1, col2, col3 = st.beta_columns(3)
142
  with col1:
143
- default_image_1 = "https://cdn.pixabay.com/photo/2014/10/13/21/34/clipper-487503_960_720.jpg"
144
  st.image(default_image_1, use_column_width=True)
145
  if st.button("Select image 1"):
146
  state.images = [default_image_1]
147
  state.default_text_input = default_text_input
148
  with col2:
149
- default_image_2 = "https://cdn.pixabay.com/photo/2019/11/11/14/30/zebra-4618513_960_720.jpg"
150
  st.image(default_image_2, use_column_width=True)
151
  if st.button("Select image 2"):
152
  state.images = [default_image_2]
153
  state.default_text_input = default_text_input
154
  with col3:
155
- default_image_3 = "https://cdn.pixabay.com/photo/2016/11/15/16/24/banana-1826760_960_720.jpg"
156
  st.image(default_image_3, use_column_width=True)
157
  if st.button("Select image 3"):
158
  state.images = [default_image_3]
@@ -161,7 +157,7 @@ class Sections:
161
  @staticmethod
162
  def dataset_picker(state: SessionState):
163
  columns = st.beta_columns(5)
164
- state.dataset = select_random_dataset()
165
  image_idx = 0
166
  for col in columns:
167
  col.image(state.dataset[image_idx])
@@ -226,61 +222,50 @@ class Sections:
226
  st.warning("Enter the prompt to classify")
227
 
228
  @staticmethod
229
- def classification_output(state: SessionState):
230
  # Possible way of customize this https://discuss.streamlit.io/t/st-button-in-a-custom-layout/2187/2
231
  if st.button("Predict") and is_valid_prediction_state(state): # PREDICT πŸš€
232
  with st.spinner("Predicting..."):
233
- if isinstance(state.images[0], str):
234
- clip_response = booste.clip(BOOSTE_API_KEY,
235
- prompts=state.prompts,
236
- images=state.images)
237
- else:
238
- images_mocker.calculate_image_id2image_lookup(state.images)
239
- images_mocker.start_mocking()
240
- clip_response = booste.clip(BOOSTE_API_KEY,
241
- prompts=state.prompts,
242
- images=images_mocker.image_ids)
243
- images_mocker.stop_mocking()
244
  st.markdown("### Results")
245
  # st.write(clip_response)
246
  if len(state.images) == 1:
247
- simplified_clip_results = [(prompt,
248
- list(results.values())[0]["probabilityRelativeToPrompts"])
249
- for prompt, results in clip_response.items()]
250
- simplified_clip_results = sorted(simplified_clip_results, key=lambda x: x[1], reverse=True)
251
-
252
- for prompt, probability in simplified_clip_results:
253
  percentage_prob = int(probability * 100)
254
  st.markdown(
255
  f"### ![prob](https://progress-bar.dev/{percentage_prob}/?width=200) &nbsp &nbsp {prompt}")
256
- else:
257
  st.markdown(f"### {state.prompts[0]}")
258
- assert len(state.prompts) == 1
259
- if isinstance(state.images[0], str):
260
- simplified_clip_results = [(image, results["probabilityRelativeToImages"]) for image, results
261
- in list(clip_response.values())[0].items()]
262
- else:
263
- simplified_clip_results = [(images_mocker.image_id2image(image),
264
- results["probabilityRelativeToImages"]) for image, results
265
- in list(clip_response.values())[0].items()]
266
- simplified_clip_results = sorted(simplified_clip_results, key=lambda x: x[1], reverse=True)
267
- for image, probability in simplified_clip_results[:5]:
268
  col1, col2 = st.beta_columns([1, 3])
269
  col1.image(image, use_column_width=True)
270
  percentage_prob = int(probability * 100)
271
  col2.markdown(f"### ![prob](https://progress-bar.dev/{percentage_prob}/?width=200)")
272
- is_default_image = isinstance(state.images[0], str)
273
- is_default_prediction = is_default_image and state.is_default_text_input
274
- if is_default_prediction:
275
- st.markdown("<br>:information_source: Try writing your own prompts and using your own pictures!",
276
- unsafe_allow_html=True)
277
- elif is_default_image:
278
- st.markdown("<br>:information_source: You can also use your own pictures!",
279
- unsafe_allow_html=True)
280
- elif state.is_default_text_input:
281
- st.markdown("<br>:information_source: Try writing your own prompts!"
282
- " It can be whatever you can think of",
283
- unsafe_allow_html=True)
 
 
 
284
 
285
 
286
  Sections.header()
@@ -290,8 +275,7 @@ col1.markdown("#### Task selection")
290
  task_name: str = col2.selectbox("", options=["Prompt ranking", "Image ranking", "Image classification"])
291
  st.markdown("<br>", unsafe_allow_html=True)
292
 
293
- images_mocker.stop_mocking() # Sometimes it gets stuck mocking
294
-
295
  session_state = get_state()
296
  if task_name == "Image classification":
297
  Sections.image_uploader(session_state, accept_multiple_files=False)
@@ -302,7 +286,7 @@ if task_name == "Image classification":
302
  Sections.prompts_input(session_state, input_label, prompt_prefix='A picture of a ')
303
  limit_number_images(session_state)
304
  Sections.single_image_input_preview(session_state)
305
- Sections.classification_output(session_state)
306
  elif task_name == "Prompt ranking":
307
  Sections.image_uploader(session_state, accept_multiple_files=False)
308
  if session_state.images is None:
@@ -315,7 +299,7 @@ elif task_name == "Prompt ranking":
315
  Sections.prompts_input(session_state, input_label)
316
  limit_number_images(session_state)
317
  Sections.single_image_input_preview(session_state)
318
- Sections.classification_output(session_state)
319
  elif task_name == "Image ranking":
320
  Sections.image_uploader(session_state, accept_multiple_files=True)
321
  if session_state.images is None or len(session_state.images) < 2:
@@ -324,7 +308,7 @@ elif task_name == "Image ranking":
324
  Sections.prompts_input(session_state, "Enter the prompt to query the images by")
325
  limit_number_prompts(session_state)
326
  Sections.multiple_images_input_preview(session_state)
327
- Sections.classification_output(session_state)
328
 
329
  st.markdown("<br><br><br><br>Made by [@JavierFnts](https://twitter.com/JavierFnts) | [How was CLIP Playground built?](https://twitter.com/JavierFnts/status/1363522529072214019)"
330
  "", unsafe_allow_html=True)
 
1
  import random
2
+ import requests
3
 
4
  import streamlit as st
5
+ from clip_model import ClipModel
6
 
7
  from session_state import SessionState, get_state
8
  from images_mocker import ImagesMocker
9
 
 
 
 
10
  from PIL import Image
11
 
 
 
 
 
12
  IMAGES_LINKS = ["https://cdn.pixabay.com/photo/2014/10/13/21/34/clipper-487503_960_720.jpg",
13
  "https://cdn.pixabay.com/photo/2019/09/06/04/25/beach-4455433_960_720.jpg",
 
 
 
 
14
  "https://cdn.pixabay.com/photo/2019/11/11/14/30/zebra-4618513_960_720.jpg",
15
  "https://cdn.pixabay.com/photo/2020/11/04/15/29/coffee-beans-5712780_960_720.jpg",
16
  "https://cdn.pixabay.com/photo/2020/03/24/20/42/namibia-4965457_960_720.jpg",
17
  "https://cdn.pixabay.com/photo/2020/08/27/07/31/restaurant-5521372_960_720.jpg",
 
18
  "https://cdn.pixabay.com/photo/2020/08/24/21/41/couple-5515141_960_720.jpg",
19
  "https://cdn.pixabay.com/photo/2020/01/31/07/10/billboards-4807268_960_720.jpg",
20
  "https://cdn.pixabay.com/photo/2017/07/31/20/48/shell-2560930_960_720.jpg",
21
  "https://cdn.pixabay.com/photo/2020/08/13/01/29/koala-5483931_960_720.jpg",
 
22
  ]
23
 
24
  @st.cache # Cache this so that it doesn't change every time something changes in the page
25
+ def load_default_dataset():
26
+ return [load_image_from_url(url) for url in IMAGES_LINKS]
27
+
28
+ def load_image_from_url(url: str) -> Image.Image:
29
+ return Image.open(requests.get(url, stream=True).raw)
30
+
31
+ @st.cache
32
+ def load_model() -> ClipModel:
33
+ return ClipModel()
34
 
35
 
36
  def limit_number_images(state: SessionState):
 
136
  def image_picker(state: SessionState, default_text_input: str):
137
  col1, col2, col3 = st.beta_columns(3)
138
  with col1:
139
+ default_image_1 = load_image_from_url("https://cdn.pixabay.com/photo/2014/10/13/21/34/clipper-487503_960_720.jpg")
140
  st.image(default_image_1, use_column_width=True)
141
  if st.button("Select image 1"):
142
  state.images = [default_image_1]
143
  state.default_text_input = default_text_input
144
  with col2:
145
+ default_image_2 = load_image_from_url("https://cdn.pixabay.com/photo/2019/11/11/14/30/zebra-4618513_960_720.jpg")
146
  st.image(default_image_2, use_column_width=True)
147
  if st.button("Select image 2"):
148
  state.images = [default_image_2]
149
  state.default_text_input = default_text_input
150
  with col3:
151
+ default_image_3 = load_image_from_url("https://cdn.pixabay.com/photo/2016/11/15/16/24/banana-1826760_960_720.jpg")
152
  st.image(default_image_3, use_column_width=True)
153
  if st.button("Select image 3"):
154
  state.images = [default_image_3]
 
157
  @staticmethod
158
  def dataset_picker(state: SessionState):
159
  columns = st.beta_columns(5)
160
+ state.dataset = load_default_dataset()
161
  image_idx = 0
162
  for col in columns:
163
  col.image(state.dataset[image_idx])
 
222
  st.warning("Enter the prompt to classify")
223
 
224
  @staticmethod
225
+ def classification_output(state: SessionState, model: ClipModel):
226
  # Possible way of customize this https://discuss.streamlit.io/t/st-button-in-a-custom-layout/2187/2
227
  if st.button("Predict") and is_valid_prediction_state(state): # PREDICT πŸš€
228
  with st.spinner("Predicting..."):
229
+
 
 
 
 
 
 
 
 
 
 
230
  st.markdown("### Results")
231
  # st.write(clip_response)
232
  if len(state.images) == 1:
233
+ scores = model.compute_prompts_probabilities(state.images[0], state.prompts)
234
+ scored_prompts = [(prompt, score) for prompt, score in zip(state.prompts, scores)]
235
+ st.json(scores)
236
+ sorted_scored_prompts = sorted(scored_prompts, key=lambda x: x[1], reverse=True)
237
+ for prompt, probability in sorted_scored_prompts:
 
238
  percentage_prob = int(probability * 100)
239
  st.markdown(
240
  f"### ![prob](https://progress-bar.dev/{percentage_prob}/?width=200) &nbsp &nbsp {prompt}")
241
+ elif len(state.prompts) == 1:
242
  st.markdown(f"### {state.prompts[0]}")
243
+
244
+ scores = model.compute_prompts_probabilities(state.images[0], state.prompts)
245
+ scored_images = [(image, score) for image, score in zip(state.images, scores)]
246
+ st.json(scores)
247
+ sorted_scored_images = sorted(scored_prompts, key=lambda x: x[1], reverse=True)
248
+
249
+ for image, probability in sorted_scored_images[:5]:
 
 
 
250
  col1, col2 = st.beta_columns([1, 3])
251
  col1.image(image, use_column_width=True)
252
  percentage_prob = int(probability * 100)
253
  col2.markdown(f"### ![prob](https://progress-bar.dev/{percentage_prob}/?width=200)")
254
+ else:
255
+ raise ValueError("Invalid state")
256
+
257
+ # is_default_image = isinstance(state.images[0], str)
258
+ # is_default_prediction = is_default_image and state.is_default_text_input
259
+ # if is_default_prediction:
260
+ # st.markdown("<br>:information_source: Try writing your own prompts and using your own pictures!",
261
+ # unsafe_allow_html=True)
262
+ # elif is_default_image:
263
+ # st.markdown("<br>:information_source: You can also use your own pictures!",
264
+ # unsafe_allow_html=True)
265
+ # elif state.is_default_text_input:
266
+ # st.markdown("<br>:information_source: Try writing your own prompts!"
267
+ # " It can be whatever you can think of",
268
+ # unsafe_allow_html=True)
269
 
270
 
271
  Sections.header()
 
275
  task_name: str = col2.selectbox("", options=["Prompt ranking", "Image ranking", "Image classification"])
276
  st.markdown("<br>", unsafe_allow_html=True)
277
 
278
+ model = load_model()
 
279
  session_state = get_state()
280
  if task_name == "Image classification":
281
  Sections.image_uploader(session_state, accept_multiple_files=False)
 
286
  Sections.prompts_input(session_state, input_label, prompt_prefix='A picture of a ')
287
  limit_number_images(session_state)
288
  Sections.single_image_input_preview(session_state)
289
+ Sections.classification_output(session_state, model)
290
  elif task_name == "Prompt ranking":
291
  Sections.image_uploader(session_state, accept_multiple_files=False)
292
  if session_state.images is None:
 
299
  Sections.prompts_input(session_state, input_label)
300
  limit_number_images(session_state)
301
  Sections.single_image_input_preview(session_state)
302
+ Sections.classification_output(session_state, model)
303
  elif task_name == "Image ranking":
304
  Sections.image_uploader(session_state, accept_multiple_files=True)
305
  if session_state.images is None or len(session_state.images) < 2:
 
308
  Sections.prompts_input(session_state, "Enter the prompt to query the images by")
309
  limit_number_prompts(session_state)
310
  Sections.multiple_images_input_preview(session_state)
311
+ Sections.classification_output(session_state, model)
312
 
313
  st.markdown("<br><br><br><br>Made by [@JavierFnts](https://twitter.com/JavierFnts) | [How was CLIP Playground built?](https://twitter.com/JavierFnts/status/1363522529072214019)"
314
  "", unsafe_allow_html=True)