File size: 9,219 Bytes
b6c64a0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
import torch
import open_clip
from PIL import Image
import requests
import json
import gradio as gr
import pandas as pd
from io import BytesIO
import os
# Load the Amazon taxonomy from a JSON file
with open("amazon.json", "r") as f:
AMAZON_TAXONOMY = json.load(f)
base_model_name = "ViT-B-16"
model_base, _, preprocess_base = open_clip.create_model_and_transforms(base_model_name)
tokenizer_base = open_clip.get_tokenizer(base_model_name)
model_name_B = "hf-hub:Marqo/marqo-ecommerce-embeddings-B"
model_B, _, preprocess_B = open_clip.create_model_and_transforms(model_name_B)
tokenizer_B = open_clip.get_tokenizer(model_name_B)
model_name_L = "hf-hub:Marqo/marqo-ecommerce-embeddings-L"
model_L, _, preprocess_L = open_clip.create_model_and_transforms(model_name_L)
tokenizer_L = open_clip.get_tokenizer(model_name_L)
models = [base_model_name, model_name_B, model_name_L]
taxonomy_cache = {}
for model in models:
with open(f'{model.split("/")[-1]}.json', "r") as f:
taxonomy_cache[model] = json.load(f)
def cosine_similarity(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
numerator = (a * b).sum(dim=-1)
denominator = torch.linalg.norm(a, ord=2, dim=-1) * torch.linalg.norm(
b, ord=2, dim=-1
)
return 0.5 * (numerator / denominator + 1.0)
class BeamPath:
def __init__(self, path: list, cumulative_score: float, current_layer: dict | list):
self.path = path
self.cumulative_score = cumulative_score
self.current_layer = current_layer
def __repr__(self):
return f"BeamPath(path={self.path}, cumulative_score={self.cumulative_score})"
def _compute_similarities(classes: list, base_embedding: torch.Tensor, cache_key: str):
text_features = torch.tensor(
[taxonomy_cache[cache_key][class_name] for class_name in classes]
)
similarities = cosine_similarity(base_embedding, text_features)
return similarities.cpu().numpy()
def map_taxonomy(
base_image: Image.Image,
taxonomy: dict,
model,
tokenizer,
preprocess_val,
cache_key,
beam_width: int = 3,
) -> tuple[list[tuple[str, float]], float]:
image_tensor = preprocess_val(base_image).unsqueeze(0)
with torch.no_grad(), torch.cuda.amp.autocast():
base_embedding = model.encode_image(image_tensor, normalize=True)
initial_path = BeamPath(path=[], cumulative_score=0.0, current_layer=taxonomy)
beam = [initial_path]
final_paths = []
is_first = True
while beam:
candidates = []
candidate_entries = []
for beam_path in beam:
layer = beam_path.current_layer
if isinstance(layer, dict):
classes = list(layer.keys())
elif isinstance(layer, list):
classes = layer
if classes == []:
final_paths.append(beam_path)
continue
else:
final_paths.append(beam_path)
continue
# current_path_class_names = [class_name for class_name, _ in beam_path.path]
for class_name in classes:
candidate_string = class_name
if isinstance(layer, dict):
next_layer = layer[class_name]
else:
next_layer = None
candidate_entries.append(
(candidate_string, class_name, beam_path, next_layer)
)
if not candidate_entries:
break
candidate_strings = [
candidate_string for candidate_string, _, _, _ in candidate_entries
]
similarities = _compute_similarities(
candidate_strings, base_embedding, cache_key
)
for (candidate_string, class_name, beam_path, next_layer), similarity in zip(
candidate_entries, similarities
):
new_path = beam_path.path + [(class_name, float(similarity))]
new_cumulative_score = beam_path.cumulative_score + similarity
candidate = BeamPath(
path=new_path,
cumulative_score=new_cumulative_score,
current_layer=next_layer,
)
candidates.append(candidate)
from collections import defaultdict
by_parents = defaultdict(list)
for candidate in candidates:
by_parents[candidate.path[0][0]].append(candidate)
beam = []
for parent in by_parents:
children = by_parents[parent]
children.sort(
key=lambda x: x.cumulative_score / len(x.path) + x.path[-1][1],
reverse=True,
)
if is_first:
beam.extend(children)
else:
beam.extend(children[:beam_width])
is_first = False
all_paths = beam + final_paths
if all_paths:
all_paths.sort(key=lambda x: x.cumulative_score / len(x.path), reverse=True)
best_path = all_paths[0]
return best_path.path, float(best_path.cumulative_score)
else:
return [], 0.0
# Function to classify image and map taxonomy
def classify_image(
image_input: Image.Image | None,
image_url: str | None,
model_size: str,
beam_width: int,
):
if image_input is not None:
image = image_input
elif image_url:
# Try to get image from URL
try:
response = requests.get(image_url)
image = Image.open(BytesIO(response.content)).convert("RGB")
except Exception as e:
return pd.DataFrame({"Error": [str(e)]})
else:
return pd.DataFrame(
{
"Error": [
"Please provide an image, an image URL, or select an example image"
]
}
)
# Select the model, tokenizer, and preprocess
if model_size == "marqo-ecommerce-embeddings-L":
key = "hf-hub:Marqo/marqo-ecommerce-embeddings-L"
model = model_L
preprocess_val = preprocess_L
tokenizer = tokenizer_L
elif model_size == "marqo-ecommerce-embeddings-B":
key = "hf-hub:Marqo/marqo-ecommerce-embeddings-B"
model = model_B
preprocess_val = preprocess_B
tokenizer = tokenizer_B
elif model_size == "openai-ViT-B-16":
key = "ViT-B-16"
model = model_base
preprocess_val = preprocess_base
tokenizer = tokenizer_base
else:
return pd.DataFrame({"Error": ["Invalid model size"]})
path, cumulative_score = map_taxonomy(
base_image=image,
taxonomy=AMAZON_TAXONOMY,
model=model,
tokenizer=tokenizer,
preprocess_val=preprocess_val,
cache_key=key,
beam_width=beam_width,
)
output = []
for idx, (category, score) in enumerate(path):
level = idx + 1
output.append({"Level": level, "Category": category, "Score": score})
df = pd.DataFrame(output)
return df
with gr.Blocks() as demo:
gr.Markdown("# Image Classification with Taxonomy Mapping")
gr.Markdown(
"## How to use this app\n\nThis app compares Marqo's E-commerce embeddings to OpenAI's ViT-B-16 CLIP model for E-commerce taxonomy mapping. A beam search is used to find the correct classification in the taxonomy. The original OpenAI CLIP models perform very poorly on E-commerce data."
)
gr.Markdown(
"Upload an image, provide an image URL, or select an example image, select the model size, and get the taxonomy mapping. The taxonomy is based on the Amazon product taxonomy."
)
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Upload Image", height=300)
image_url_input = gr.Textbox(
lines=1, placeholder="Image URL", label="Image URL"
)
gr.Markdown("### Or select an example image:")
# Get example images from 'images' folder
example_images_folder = "images"
example_image_paths = [
os.path.join(example_images_folder, img)
for img in os.listdir(example_images_folder)
]
gr.Examples(
examples=[[img_path] for img_path in example_image_paths],
inputs=image_input,
label="Example Images",
examples_per_page=100,
)
with gr.Column():
model_size_input = gr.Radio(
choices=[
"marqo-ecommerce-embeddings-L",
"marqo-ecommerce-embeddings-B",
"openai-ViT-B-16",
],
label="Model",
value="marqo-ecommerce-embeddings-L",
)
beam_width_input = gr.Number(
label="Beam Width", value=5, minimum=1, step=1
)
classify_button = gr.Button("Classify")
output_table = gr.Dataframe(headers=["Level", "Category", "Score"])
classify_button.click(
fn=classify_image,
inputs=[image_input, image_url_input, model_size_input, beam_width_input],
outputs=output_table,
)
demo.launch()
|