Reverse Image Search for a Product Catalog with CLIP and pgvector
PYTHONCLIPPGVECTORMACHINE LEARNINGSEARCH
A customer sees a product in a photo and wants it, but does not know what it is called, what size it is, or what the shop named it. Typing words into a search box fails them. So let them search with the picture instead. I built the piece that takes an uploaded photo and returns the closest products from the catalog.
The idea
Every product image gets turned into a list of numbers, an embedding, that captures what it looks like. An uploaded photo gets the same treatment, and then the question is which catalog vectors sit closest to it. CLIP produces the embeddings, Postgres with the pgvector extension stores them, and a cosine-distance index finds the nearest matches quickly.The bug that would have been invisible
The risk here is a search that returns wrong results while looking completely normal. If the images are embedded with one model and the queries with another, every search still returns something. It is just wrong, and nothing tells you. The same happens if the preprocessing differs slightly between the indexing side and the query side. I fixed it two ways. There is exactly one place in the code that turns pixels into a vector, and both the indexer and the search call it, so they cannot drift apart. And every stored vector is stamped with the model and weights that made it. Change the model and the stamp changes, which makes a stale index visible instead of silently wrong; a re-embed job just looks for rows whose stamp no longer matches.Keeping the shop up
The model is heavy. Loading it into the same process that serves the website means one burst of uploads can slow the whole shop down. So the encoder runs in its own small service, and the main application talks to it over the network. If that service falls over, image search returns a clean error and the rest of the shop, browsing and cart and checkout, keeps working. I also built the throwaway prototype first, against a folder of images, so I got the embedding and the index right in isolation before any of it touched the real product.Results
- Customers find products from a photo instead of guessing search terms
- Embeddings stored in Postgres with pgvector, nearest match over a cosine index
- Stale or mismatched vectors are detectable by design, not found through a complaint
- The encoder is isolated, so an inference spike cannot take the storefront down