e-comm-flask / image_tool.py
abdullah9873's picture
Upload folder using huggingface_hub
3c62f53 verified
Raw History Blame Contribute Delete
2.69 kB
from PIL import Image
import numpy as np
import os
import json
import torch
import torchvision.transforms as T
import clip
from sklearn.metrics.pairwise import cosine_simila
device = "cuda" if torch.cuda.is_available() else "cpu"
# Load CLIP model
model, preprocess = clip.load("ViT-B/32", device=device)
# Load product data
try:
with open("products.json", "r") as f:
products = json.load(f)["products"]
except Exception as e:
print(f"❌ Failed to load product data: {e}")
products = []
# Get image embedding
def get_image_embedding(image_path):
try:
image = Image.open(image_path).convert("RGB")
image_input = preprocess(image).unsqueeze(0).to(device)
with torch.no_grad():
image_features = model.encode_image(image_input)
return image_features.cpu().numpy()
except Exception as e:
print(f"❌ Failed to process image {image_path}: {e}")
return None
# Precompute product image embeddings
product_vectors = []
for product in products:
image_path = product.get("image")
if image_path and os.path.exists(image_path):
emb = get_image_embedding(image_path)
if emb is not None:
product_vectors.append((product, emb))
print(f"βœ… Image processed: {image_path}")
else:
print(f"⚠️ Image not found: {image_path}")
# Match uploaded image with most similar product
def find_product_by_image(uploaded_image: Image.Image):
try:
uploaded_image = uploaded_image.convert("RGB")
image_input = preprocess(uploaded_image).unsqueeze(0).to(device)
with torch.no_grad():
uploaded_features = model.encode_image(image_input).cpu().numpy()
max_sim = -1
matched_product = None
for product, emb in product_vectors:
sim = cosine_similarity(uploaded_features, emb)[0][0]
if sim > max_sim:
max_sim = sim
matched_product = product
return matched_product
except Exception as e:
print(f"❌ Failed to find product: {e}")
return None
# Example test (run only if this is the main script)
if __name__ == "__main__":
test_path = "static/images/sofa1.webp"
if os.path.exists(test_path):
uploaded_img = Image.open(test_path)
result = find_product_by_image(uploaded_img)
if result:
print("βœ… Matched Product:")
print(json.dumps(result, indent=2))
else:
print("❌ No similar product found.")
else:
print(f"❌ Uploaded image not found: {test_path}")