Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import open_clip
|
3 |
+
import torch
|
4 |
+
import requests
|
5 |
+
from PIL import Image
|
6 |
+
from io import BytesIO
|
7 |
+
import time
|
8 |
+
import json
|
9 |
+
import numpy as np
|
10 |
+
import cv2
|
11 |
+
import chromadb
|
12 |
+
from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor
|
13 |
+
|
14 |
+
# Load CLIP model and tokenizer
|
15 |
+
@st.cache_resource
|
16 |
+
def load_clip_model():
|
17 |
+
model, preprocess_train, preprocess_val = open_clip.create_model_and_transforms('hf-hub:Marqo/marqo-fashionSigLIP')
|
18 |
+
tokenizer = open_clip.get_tokenizer('hf-hub:Marqo/marqo-fashionSigLIP')
|
19 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
20 |
+
model.to(device)
|
21 |
+
return model, preprocess_val, tokenizer, device
|
22 |
+
|
23 |
+
clip_model, preprocess_val, tokenizer, device = load_clip_model()
|
24 |
+
|
25 |
+
# Load SegFormer model
|
26 |
+
@st.cache_resource
|
27 |
+
def load_segformer_model():
|
28 |
+
model = SegformerForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes")
|
29 |
+
processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")
|
30 |
+
return model, processor
|
31 |
+
|
32 |
+
segformer_model, segformer_processor = load_segformer_model()
|
33 |
+
|
34 |
+
# Helper functions
|
35 |
+
def load_image_from_url(url, max_retries=3):
|
36 |
+
for attempt in range(max_retries):
|
37 |
+
try:
|
38 |
+
response = requests.get(url, timeout=10)
|
39 |
+
response.raise_for_status()
|
40 |
+
img = Image.open(BytesIO(response.content)).convert('RGB')
|
41 |
+
return img
|
42 |
+
except (requests.RequestException, Image.UnidentifiedImageError) as e:
|
43 |
+
if attempt < max_retries - 1:
|
44 |
+
time.sleep(1)
|
45 |
+
else:
|
46 |
+
return None
|
47 |
+
|
48 |
+
#Load chromaDB
|
49 |
+
client = chromadb.PersistentClient(path="./clothesDB")
|
50 |
+
collection = client.get_collection(name="clothes_items_ver3")
|
51 |
+
|
52 |
+
def get_image_embedding(image):
|
53 |
+
image_tensor = preprocess_val(image).unsqueeze(0).to(device)
|
54 |
+
with torch.no_grad():
|
55 |
+
image_features = clip_model.encode_image(image_tensor)
|
56 |
+
image_features /= image_features.norm(dim=-1, keepdim=True)
|
57 |
+
return image_features.cpu().numpy()
|
58 |
+
|
59 |
+
def get_text_embedding(text):
|
60 |
+
text_tokens = tokenizer([text]).to(device)
|
61 |
+
with torch.no_grad():
|
62 |
+
text_features = clip_model.encode_text(text_tokens)
|
63 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
64 |
+
return text_features.cpu().numpy()
|
65 |
+
|
66 |
+
def get_all_embeddings_from_collection(collection):
|
67 |
+
all_embeddings = collection.get(include=['embeddings'])['embeddings']
|
68 |
+
return np.array(all_embeddings)
|
69 |
+
|
70 |
+
def get_metadata_from_ids(collection, ids):
|
71 |
+
results = collection.get(ids=ids)
|
72 |
+
return results['metadatas']
|
73 |
+
|
74 |
+
def find_similar_images(query_embedding, collection, top_k=5):
|
75 |
+
database_embeddings = get_all_embeddings_from_collection(collection)
|
76 |
+
similarities = np.dot(database_embeddings, query_embedding.T).squeeze()
|
77 |
+
top_indices = np.argsort(similarities)[::-1][:top_k]
|
78 |
+
|
79 |
+
all_data = collection.get(include=['metadatas'])['metadatas']
|
80 |
+
|
81 |
+
top_metadatas = [all_data[idx] for idx in top_indices]
|
82 |
+
|
83 |
+
results = []
|
84 |
+
for idx, metadata in enumerate(top_metadatas):
|
85 |
+
results.append({
|
86 |
+
'info': metadata,
|
87 |
+
'similarity': similarities[top_indices[idx]]
|
88 |
+
})
|
89 |
+
return results
|
90 |
+
|
91 |
+
def segment_clothing(image):
|
92 |
+
inputs = segformer_processor(images=image, return_tensors="pt")
|
93 |
+
outputs = segformer_model(**inputs)
|
94 |
+
logits = outputs.logits.squeeze()
|
95 |
+
predicted_mask = logits.argmax(dim=0).numpy()
|
96 |
+
|
97 |
+
categories = segformer_model.config.id2label
|
98 |
+
segmented_items = []
|
99 |
+
|
100 |
+
for category_id, category_name in categories.items():
|
101 |
+
if category_id in predicted_mask:
|
102 |
+
mask = (predicted_mask == category_id).astype(np.uint8)
|
103 |
+
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
104 |
+
if contours:
|
105 |
+
x, y, w, h = cv2.boundingRect(max(contours, key=cv2.contourArea))
|
106 |
+
segmented_items.append({
|
107 |
+
'category': category_name,
|
108 |
+
'bbox': [x, y, x+w, y+h],
|
109 |
+
'mask': mask
|
110 |
+
})
|
111 |
+
|
112 |
+
return segmented_items
|
113 |
+
|
114 |
+
def crop_image(image, bbox):
|
115 |
+
return image.crop((bbox[0], bbox[1], bbox[2], bbox[3]))
|
116 |
+
|
117 |
+
# Streamlit app
|
118 |
+
st.title("Advanced Fashion Search App")
|
119 |
+
|
120 |
+
# Initialize session state
|
121 |
+
if 'step' not in st.session_state:
|
122 |
+
st.session_state.step = 'input'
|
123 |
+
if 'query_image_url' not in st.session_state:
|
124 |
+
st.session_state.query_image_url = ''
|
125 |
+
if 'segmentations' not in st.session_state:
|
126 |
+
st.session_state.segmentations = []
|
127 |
+
if 'selected_category' not in st.session_state:
|
128 |
+
st.session_state.selected_category = None
|
129 |
+
|
130 |
+
# Step-by-step processing
|
131 |
+
if st.session_state.step == 'input':
|
132 |
+
st.session_state.query_image_url = st.text_input("Enter image URL:", st.session_state.query_image_url)
|
133 |
+
if st.button("Segment Clothing"):
|
134 |
+
if st.session_state.query_image_url:
|
135 |
+
query_image = load_image_from_url(st.session_state.query_image_url)
|
136 |
+
if query_image is not None:
|
137 |
+
st.session_state.query_image = query_image
|
138 |
+
st.session_state.segmentations = segment_clothing(query_image)
|
139 |
+
if st.session_state.segmentations:
|
140 |
+
st.session_state.step = 'select_category'
|
141 |
+
else:
|
142 |
+
st.warning("No clothing items segmented in the image.")
|
143 |
+
else:
|
144 |
+
st.error("Failed to load the image. Please try another URL.")
|
145 |
+
else:
|
146 |
+
st.warning("Please enter an image URL.")
|
147 |
+
|
148 |
+
elif st.session_state.step == 'select_category':
|
149 |
+
st.image(st.session_state.query_image, caption="Query Image", use_column_width=True)
|
150 |
+
st.subheader("Segmented Clothing Items:")
|
151 |
+
|
152 |
+
for segmentation in st.session_state.segmentations:
|
153 |
+
col1, col2 = st.columns([1, 3])
|
154 |
+
with col1:
|
155 |
+
st.write(f"{segmentation['category']}")
|
156 |
+
with col2:
|
157 |
+
cropped_image = crop_image(st.session_state.query_image, segmentation['bbox'])
|
158 |
+
st.image(cropped_image, caption=segmentation['category'], use_column_width=True)
|
159 |
+
|
160 |
+
options = [s['category'] for s in st.session_state.segmentations]
|
161 |
+
selected_option = st.selectbox("Select a category to search:", options)
|
162 |
+
|
163 |
+
if st.button("Search Similar Items"):
|
164 |
+
st.session_state.selected_category = selected_option
|
165 |
+
st.session_state.step = 'show_results'
|
166 |
+
|
167 |
+
elif st.session_state.step == 'show_results':
|
168 |
+
st.image(st.session_state.query_image, caption="Query Image", use_column_width=True)
|
169 |
+
selected_segmentation = next(s for s in st.session_state.segmentations
|
170 |
+
if s['category'] == st.session_state.selected_category)
|
171 |
+
cropped_image = crop_image(st.session_state.query_image, selected_segmentation['bbox'])
|
172 |
+
st.image(cropped_image, caption="Cropped Image", use_column_width=True)
|
173 |
+
query_embedding = get_image_embedding(cropped_image)
|
174 |
+
similar_images = find_similar_images(query_embedding, collection)
|
175 |
+
|
176 |
+
st.subheader("Similar Items:")
|
177 |
+
for img in similar_images:
|
178 |
+
col1, col2 = st.columns(2)
|
179 |
+
with col1:
|
180 |
+
st.image(img['info']['image_url'], use_column_width=True)
|
181 |
+
with col2:
|
182 |
+
st.write(f"Name: {img['info']['name']}")
|
183 |
+
st.write(f"Brand: {img['info']['brand']}")
|
184 |
+
category = img['info'].get('category')
|
185 |
+
if category:
|
186 |
+
st.write(f"Category: {category}")
|
187 |
+
st.write(f"Price: {img['info']['price']}")
|
188 |
+
st.write(f"Discount: {img['info']['discount']}%")
|
189 |
+
st.write(f"Similarity: {img['similarity']:.2f}")
|
190 |
+
|
191 |
+
if st.button("Start New Search"):
|
192 |
+
st.session_state.step = 'input'
|
193 |
+
st.session_state.query_image_url = ''
|
194 |
+
st.session_state.segmentations = []
|
195 |
+
st.session_state.selected_category = None
|
196 |
+
|
197 |
+
else: # Text search
|
198 |
+
query_text = st.text_input("Enter search text:")
|
199 |
+
if st.button("Search by Text"):
|
200 |
+
if query_text:
|
201 |
+
text_embedding = get_text_embedding(query_text)
|
202 |
+
similar_images = find_similar_images(text_embedding, collection)
|
203 |
+
st.subheader("Similar Items:")
|
204 |
+
for img in similar_images:
|
205 |
+
col1, col2 = st.columns(2)
|
206 |
+
with col1:
|
207 |
+
st.image(img['info']['image_url'], use_column_width=True)
|
208 |
+
with col2:
|
209 |
+
st.write(f"Name: {img['info']['name']}")
|
210 |
+
st.write(f"Brand: {img['info']['brand']}")
|
211 |
+
category = img['info'].get('category')
|
212 |
+
if category:
|
213 |
+
st.write(f"Category: {category}")
|
214 |
+
st.write(f"Price: {img['info']['price']}")
|
215 |
+
st.write(f"Discount: {img['info']['discount']}%")
|
216 |
+
st.write(f"Similarity: {img['similarity']:.2f}")
|
217 |
+
else:
|
218 |
+
st.warning("Please enter a search text.")
|