File size: 2,689 Bytes
3c62f53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}")