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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
if __name__ == '__main__':
|
8 |
app.run(host='0.0.0.0', port=7860)
|
|
|
2 |
sys.stdout.reconfigure(line_buffering=True)
|
3 |
|
4 |
|
5 |
+
import os
|
6 |
+
import numpy as np
|
7 |
+
import requests
|
8 |
+
import cv2
|
9 |
+
from skimage import feature
|
10 |
+
from io import BytesIO
|
11 |
+
import traceback
|
12 |
|
13 |
+
from flask import Flask, request, jsonify
|
14 |
+
from PIL import Image
|
15 |
+
|
16 |
+
# import deep learning libraries
|
17 |
+
import torch
|
18 |
+
from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection, AutoTokenizer, AutoModel
|
19 |
+
from segment_anything import SamPredictor, sam_model_registry
|
20 |
+
|
21 |
+
app = Flask(__name__)
|
22 |
+
|
23 |
+
# sum = 1
|
24 |
+
FEATURE_WEIGHTS = {
|
25 |
+
"shape": 0.4,
|
26 |
+
"color": 0.5,
|
27 |
+
"texture": 0.1
|
28 |
+
}
|
29 |
+
|
30 |
+
# threshold
|
31 |
+
FINAL_SCORE_THRESHOLD = 0.5
|
32 |
+
|
33 |
+
|
34 |
+
# load all models
|
35 |
+
print("="*50)
|
36 |
+
print("π Initializing application and loading models...")
|
37 |
+
device_name = os.environ.get("device", "cpu")
|
38 |
+
device = torch.device('cuda' if 'cuda' in device_name and torch.cuda.is_available() else 'cpu')
|
39 |
+
print(f"π§ Using device: {device}")
|
40 |
+
|
41 |
+
print("...Loading Grounding DINO model...")
|
42 |
+
gnd_model_id = "IDEA-Research/grounding-dino-tiny"
|
43 |
+
processor_gnd = AutoProcessor.from_pretrained(gnd_model_id)
|
44 |
+
model_gnd = AutoModelForZeroShotObjectDetection.from_pretrained(gnd_model_id).to(device)
|
45 |
+
|
46 |
+
print("...Loading Segment Anything (SAM) model...")
|
47 |
+
sam_checkpoint = "sam_vit_b_01ec64.pth"
|
48 |
+
sam_model = sam_model_registry["vit_b"](checkpoint=sam_checkpoint).to(device)
|
49 |
+
predictor = SamPredictor(sam_model)
|
50 |
+
|
51 |
+
print("...Loading BGE model for text embeddings...")
|
52 |
+
bge_model_id = "BAAI/bge-small-en-v1.5"
|
53 |
+
tokenizer_text = AutoTokenizer.from_pretrained(bge_model_id)
|
54 |
+
model_text = AutoModel.from_pretrained(bge_model_id).to(device)
|
55 |
+
print("β
All models loaded successfully.")
|
56 |
+
print("="*50)
|
57 |
+
|
58 |
+
|
59 |
+
# helper functions
|
60 |
+
|
61 |
+
def get_canonical_label(object_name_phrase: str) -> str:
|
62 |
+
print(f"\n [Label] Extracting label for: '{object_name_phrase}'")
|
63 |
+
label = object_name_phrase.strip().lower().split()[-1]
|
64 |
+
label = ''.join(filter(str.isalpha, label))
|
65 |
+
print(f" [Label] β
Extracted label: '{label}'")
|
66 |
+
return label if label else "unknown"
|
67 |
+
|
68 |
+
def download_image_from_url(image_url: str) -> Image.Image:
|
69 |
+
print(f" [Download] Downloading image from: {image_url[:80]}...")
|
70 |
+
response = requests.get(image_url)
|
71 |
+
response.raise_for_status()
|
72 |
+
image = Image.open(BytesIO(response.content))
|
73 |
+
image_rgb = image.convert("RGB")
|
74 |
+
print(" [Download] β
Image downloaded and standardized to RGB.")
|
75 |
+
return image_rgb
|
76 |
+
|
77 |
+
def detect_and_crop(image: Image.Image, object_name: str) -> Image.Image:
|
78 |
+
print(f"\n [Detect & Crop] Starting detection for object: '{object_name}'")
|
79 |
+
image_np = np.array(image.convert("RGB"))
|
80 |
+
height, width = image_np.shape[:2]
|
81 |
+
prompt = [[f"a {object_name}"]]
|
82 |
+
inputs = processor_gnd(images=image, text=prompt, return_tensors="pt").to(device)
|
83 |
+
with torch.no_grad():
|
84 |
+
outputs = model_gnd(**inputs)
|
85 |
+
results = processor_gnd.post_process_grounded_object_detection(
|
86 |
+
outputs, inputs.input_ids, box_threshold=0.4, text_threshold=0.3, target_sizes=[(height, width)]
|
87 |
+
)
|
88 |
+
if not results or len(results[0]['boxes']) == 0:
|
89 |
+
print(" [Detect & Crop] β Warning: Grounding DINO did not detect the object. Using full image.")
|
90 |
+
return image
|
91 |
+
result = results[0]
|
92 |
+
scores = result['scores']
|
93 |
+
max_idx = int(torch.argmax(scores))
|
94 |
+
box = result['boxes'][max_idx].cpu().numpy().astype(int)
|
95 |
+
print(f" [Detect & Crop] β
Object detected with confidence: {scores[max_idx]:.2f}, Box: {box}")
|
96 |
+
x1, y1, x2, y2 = box
|
97 |
+
|
98 |
+
predictor.set_image(image_np)
|
99 |
+
box_prompt = np.array([[x1, y1, x2, y2]])
|
100 |
+
masks, _, _ = predictor.predict(box=box_prompt, multimask_output=False)
|
101 |
+
mask = masks[0]
|
102 |
+
|
103 |
+
mask_bool = mask > 0
|
104 |
+
cropped_img_rgba = np.zeros((height, width, 4), dtype=np.uint8)
|
105 |
+
cropped_img_rgba[:, :, :3] = image_np
|
106 |
+
cropped_img_rgba[:, :, 3] = mask_bool * 255
|
107 |
+
|
108 |
+
cropped_img_rgba = cropped_img_rgba[y1:y2, x1:x2]
|
109 |
+
|
110 |
+
object_image = Image.fromarray(cropped_img_rgba, 'RGBA')
|
111 |
+
return object_image
|
112 |
+
|
113 |
+
def extract_features(segmented_image: Image.Image) -> dict:
|
114 |
+
image_rgba = np.array(segmented_image)
|
115 |
+
if image_rgba.shape[2] != 4:
|
116 |
+
raise ValueError("Segmented image must be RGBA")
|
117 |
+
|
118 |
+
b, g, r, a = cv2.split(image_rgba)
|
119 |
+
image_rgb = cv2.merge((b, g, r))
|
120 |
+
mask = a
|
121 |
+
|
122 |
+
gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY)
|
123 |
+
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
124 |
+
hu_moments = cv2.HuMoments(cv2.moments(contours[0])).flatten() if contours else np.zeros(7)
|
125 |
+
|
126 |
+
color_hist = cv2.calcHist([image_rgb], [0, 1, 2], mask, [8, 8, 8], [0, 256, 0, 256, 0, 256])
|
127 |
+
cv2.normalize(color_hist, color_hist)
|
128 |
+
color_hist = color_hist.flatten()
|
129 |
+
|
130 |
+
gray_masked = cv2.bitwise_and(gray, gray, mask=mask)
|
131 |
+
lbp = feature.local_binary_pattern(gray_masked, P=24, R=3, method="uniform")
|
132 |
+
(texture_hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, 27), range=(0, 26))
|
133 |
+
texture_hist = texture_hist.astype("float32")
|
134 |
+
texture_hist /= (texture_hist.sum() + 1e-6)
|
135 |
+
|
136 |
+
return {
|
137 |
+
"shape_features": hu_moments.tolist(),
|
138 |
+
"color_features": color_hist.tolist(),
|
139 |
+
"texture_features": texture_hist.tolist()
|
140 |
+
}
|
141 |
+
|
142 |
+
def get_text_embedding(text: str) -> list:
|
143 |
+
print(f" [Embedding] Generating text embedding for: '{text[:50]}...'")
|
144 |
+
text_with_instruction = f"Represent this sentence for searching relevant passages: {text}"
|
145 |
+
inputs = tokenizer_text(text_with_instruction, return_tensors='pt', padding=True, truncation=True, max_length=512).to(device)
|
146 |
+
with torch.no_grad():
|
147 |
+
outputs = model_text(**inputs)
|
148 |
+
embedding = outputs.last_hidden_state[:, 0, :]
|
149 |
+
embedding = torch.nn.functional.normalize(embedding, p=2, dim=1)
|
150 |
+
print(" [Embedding] β
Text embedding generated.")
|
151 |
+
return embedding.cpu().numpy()[0].tolist()
|
152 |
+
|
153 |
+
def cosine_similarity(vec1: np.ndarray, vec2: np.ndarray) -> float:
|
154 |
+
return float(np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2)))
|
155 |
+
|
156 |
+
# API endpoints
|
157 |
+
|
158 |
+
@app.route('/process', methods=['POST'])
|
159 |
+
def process_item():
|
160 |
+
"""
|
161 |
+
Receives item details, processes them, and returns all computed features.
|
162 |
+
This is called when a new item is created in the Node.js backend.
|
163 |
+
"""
|
164 |
+
print("\n" + "="*50)
|
165 |
+
print("β‘ [Request] Received new request to /process")
|
166 |
+
try:
|
167 |
+
data = request.get_json()
|
168 |
+
if not data:
|
169 |
+
return jsonify({"error": "Invalid JSON payload"}), 400
|
170 |
+
|
171 |
+
object_name = data.get('objectName')
|
172 |
+
description = data.get('objectDescription')
|
173 |
+
image_url = data.get('objectImage') # This can now be null
|
174 |
+
|
175 |
+
if not all([object_name, description]):
|
176 |
+
return jsonify({"error": "objectName and objectDescription are required."}), 400
|
177 |
+
|
178 |
+
# process text based features
|
179 |
+
canonical_label = get_canonical_label(object_name)
|
180 |
+
text_embedding = get_text_embedding(description)
|
181 |
+
|
182 |
+
response_data = {
|
183 |
+
"canonicalLabel": canonical_label,
|
184 |
+
"text_embedding": text_embedding,
|
185 |
+
}
|
186 |
+
|
187 |
+
# process visual features ONLY if an image_url is provided
|
188 |
+
if image_url:
|
189 |
+
print("--- Image URL provided, processing visual features... ---")
|
190 |
+
image = download_image_from_url(image_url)
|
191 |
+
object_crop = detect_and_crop(image, canonical_label)
|
192 |
+
visual_features = extract_features(object_crop)
|
193 |
+
# Add visual features to the response
|
194 |
+
response_data.update(visual_features)
|
195 |
+
else:
|
196 |
+
print("--- No image URL provided, skipping visual feature extraction. ---")
|
197 |
+
|
198 |
+
print("β
Successfully processed item.")
|
199 |
+
print("="*50)
|
200 |
+
return jsonify(response_data), 200
|
201 |
+
|
202 |
+
except Exception as e:
|
203 |
+
print(f"β Error in /process: {e}")
|
204 |
+
traceback.print_exc()
|
205 |
+
return jsonify({"error": str(e)}), 500
|
206 |
+
|
207 |
+
def stretch_image_score(score):
|
208 |
+
if score < 0.4 or score == 1.0:
|
209 |
+
return score
|
210 |
+
# increase confidence
|
211 |
+
return 0.7 + (score - 0.4) * (0.99 - 0.7) / (1.0 - 0.4)
|
212 |
+
|
213 |
+
@app.route('/compare', methods=['POST'])
|
214 |
+
def compare_items():
|
215 |
+
print("\n" + "="*50)
|
216 |
+
print("β‘ [Request] Received new request to /compare")
|
217 |
+
try:
|
218 |
+
data = request.get_json()
|
219 |
+
if not data:
|
220 |
+
return jsonify({"error": "Invalid JSON payload"}), 400
|
221 |
+
|
222 |
+
query_item = data.get('queryItem')
|
223 |
+
search_list = data.get('searchList')
|
224 |
+
|
225 |
+
if not all([query_item, search_list]):
|
226 |
+
return jsonify({"error": "queryItem and searchList are required."}), 400
|
227 |
+
|
228 |
+
query_text_emb = np.array(query_item['text_embedding'])
|
229 |
+
results = []
|
230 |
+
print(f"--- Comparing 1 query item against {len(search_list)} items ---")
|
231 |
+
|
232 |
+
for item in search_list:
|
233 |
+
item_id = item.get('_id')
|
234 |
+
print(f"\n [Checking] Item ID: {item_id}")
|
235 |
+
try:
|
236 |
+
# Text comparison is always done
|
237 |
+
text_emb_found = np.array(item['text_embedding'])
|
238 |
+
text_score = cosine_similarity(query_text_emb, text_emb_found)
|
239 |
+
print(f" - Text Score: {text_score:.4f}")
|
240 |
+
|
241 |
+
# --- NEW: Check if BOTH items have visual features ---
|
242 |
+
has_query_image = 'shape_features' in query_item and query_item['shape_features']
|
243 |
+
has_item_image = 'shape_features' in item and item['shape_features']
|
244 |
+
|
245 |
+
if has_query_image and has_item_image:
|
246 |
+
print(" - Both items have images. Performing visual comparison.")
|
247 |
+
# If both have images, proceed with full comparison
|
248 |
+
query_shape_feat = np.array(query_item['shape_features'])
|
249 |
+
query_color_feat = np.array(query_item['color_features']).astype("float32")
|
250 |
+
query_texture_feat = np.array(query_item['texture_features']).astype("float32")
|
251 |
+
|
252 |
+
found_shape = np.array(item['shape_features'])
|
253 |
+
found_color = np.array(item['color_features']).astype("float32")
|
254 |
+
found_texture = np.array(item['texture_features']).astype("float32")
|
255 |
+
|
256 |
+
shape_dist = cv2.matchShapes(query_shape_feat, found_shape, cv2.CONTOURS_MATCH_I1, 0.0)
|
257 |
+
shape_score = 1.0 / (1.0 + shape_dist)
|
258 |
+
color_score = cv2.compareHist(query_color_feat, found_color, cv2.HISTCMP_CORREL)
|
259 |
+
texture_score = cv2.compareHist(query_texture_feat, found_texture, cv2.HISTCMP_CORREL)
|
260 |
+
|
261 |
+
raw_image_score = (FEATURE_WEIGHTS["shape"] * shape_score +
|
262 |
+
FEATURE_WEIGHTS["color"] * color_score +
|
263 |
+
FEATURE_WEIGHTS["texture"] * texture_score)
|
264 |
+
|
265 |
+
image_score = stretch_image_score(raw_image_score)
|
266 |
+
|
267 |
+
# Weighted average of image and text scores
|
268 |
+
final_score = 0.4 * image_score + 0.6 * text_score
|
269 |
+
print(f" - Image Score: {image_score:.4f} | Final Score: {final_score:.4f}")
|
270 |
+
|
271 |
+
else:
|
272 |
+
# If one or both items lack an image, the final score is JUST the text score
|
273 |
+
print(" - One or both items missing image. Using text score only.")
|
274 |
+
final_score = text_score
|
275 |
+
|
276 |
+
# Check if the final score meets the threshold
|
277 |
+
if final_score >= FINAL_SCORE_THRESHOLD:
|
278 |
+
print(f" - β
ACCEPTED (Score >= {FINAL_SCORE_THRESHOLD})")
|
279 |
+
results.append({
|
280 |
+
"_id": item_id,
|
281 |
+
"score": round(final_score, 4),
|
282 |
+
"objectName": item.get("objectName"),
|
283 |
+
"objectDescription": item.get("objectDescription"),
|
284 |
+
"objectImage": item.get("objectImage"),
|
285 |
+
})
|
286 |
+
else:
|
287 |
+
print(f" - β REJECTED (Score < {FINAL_SCORE_THRESHOLD})")
|
288 |
+
|
289 |
+
except Exception as e:
|
290 |
+
print(f" [Skipping] Item {item_id} due to processing error: {e}")
|
291 |
+
continue
|
292 |
+
|
293 |
+
results.sort(key=lambda x: x["score"], reverse=True)
|
294 |
+
print(f"\nβ
Search complete. Found {len(results)} potential matches.")
|
295 |
+
print("="*50)
|
296 |
+
return jsonify({"matches": results}), 200
|
297 |
+
|
298 |
+
except Exception as e:
|
299 |
+
print(f"β Error in /compare: {e}")
|
300 |
+
traceback.print_exc()
|
301 |
+
return jsonify({"error": str(e)}), 500
|
302 |
if __name__ == '__main__':
|
303 |
app.run(host='0.0.0.0', port=7860)
|