The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: add image search guide.
thorwebdev16f318054d7f
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.tsindex 70f1a3cb56f..d3b5be94a9c 100644--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts@@ -885,6 +885,10 @@ export const ai: NavMenuConstant = {name: 'Headless Vector Search',url: '/guides/ai/examples/headless-vector-search',},+ {+ name: 'Image Search',+ url: '/guides/ai/examples/image-search-python',+ },{name: 'Hugging Face inference with Edge Functions',url: '/guides/ai/examples/huggingface-image-captioning',diff --git a/apps/docs/pages/guides/ai/examples/image-search-python.mdx b/apps/docs/pages/guides/ai/examples/image-search-python.mdxnew file mode 100644index 00000000000..fcfc4980c1d--- /dev/null+++ b/apps/docs/pages/guides/ai/examples/image-search-python.mdx@@ -0,0 +1,179 @@+import Layout from '~/layouts/DefaultGuideLayout'++export const meta = {+ id: 'examples-image-search-python',+ title: 'Image Search with Python',+ description: 'Implement image search with the OpenAI CLIP Model and Supabase Vector.',+}++Learn how to implement image (similarity) search using the [OpenAI CLIP Model](https://github.com/openai/CLIP), which was trained on a variety of (image, text)-pairs.++You can use the CLIP model for:++- Text-to-Image / Image-To-Text / Image-to-Image / Text-to-Text Search+- You can fine-tune it on your own image&text data with the regular SentenceTransformers training code.++[SentenceTransformers](https://www.sbert.net/examples/applications/image-search/README.html) provides models that allow to embed images and text into the same vector space. This allows to find similar images as well as to implement image search.++You can find the full application code as a Python Poetry project on [GitHub](https://github.com/supabase/supabase/tree/master/examples/ai/image_search#image-search-with-supabase-vector)++## Create a new Python Project with Poetry++[Poetry](https://python-poetry.org/) provides packaging and dependency management for Python. If you haven't already, install poetry via pip++```shell+pip install poetry+```++Then initialize a new project++```shell+poetry new image-search+```++## Setup Supabase project++If you haven't already, [install the Supabase CLI](/docs/guides/cli), then initialize Supabase in the root of your newly created poetry project:++```shell+supabase init+```++Next, start your local Supabase stack++```shell+supabase start+```++This will start up the Supabase stack locally and print out a bunch of environtment details, including your local `DB URL`. Make a note of that for later user.++## Install the Dependencies++We will need to add the following dependencies to our project:++- [`vecs`](https://github.com/supabase/vecs#vecs): Supabase Vector Python Client.+- [`sentence-transformers`](https://huggingface.co/sentence-transformers/clip-ViT-B-32): a wrapper for the OpenAI CLIP Model+- [`matplotlib`](https://matplotlib.org/): for displaying our image result++```shell+poetry add vecs sentence-transformers matplotlib+```++## Import the necessary dependencies++At the top of your main python script, import the needed dependencies and store your `DB URL` from above in a variable:++```python+import sys+from PIL import Image+from sentence_transformers import SentenceTransformer+import vecs+from matplotlib import pyplot as plt+from matplotlib import image as mpimg++DB_CONNECTION = "postgresql://postgres:postgres@localhost:54322/postgres"+```++## Create embeddings for your images++In the root of your project, create a new folder called `images` and add some images. You con use the images from the example project on [GitHub](https://github.com/supabase/supabase/tree/master/examples/ai/image_search/images) or you can find license free images on [unsplash](https://unsplash.com).++Next, create a `seed` method, which will create a new Supabase Vector Collection, generate embeddings for your images, and upsert the embeddings into your database:++```python+def seed():+ # create vector store client+ vx = vecs.create_client(DB_CONNECTION)++ # create a collection of vectors with 3 dimensions+ images = vx.create_collection(name="image_vectors", dimension=512)++ # Load CLIP model+ model = SentenceTransformer('clip-ViT-B-32')++ # Encode an image:+ img_emb1 = model.encode(Image.open('./images/one.jpg'))+ img_emb2 = model.encode(Image.open('./images/two.jpg'))+ img_emb3 = model.encode(Image.open('./images/three.jpg'))+ img_emb4 = model.encode(Image.open('./images/four.jpg'))++ # add records to the *images* collection+ images.upsert(+ vectors=[+ (+ "one.jpg", # the vector's identifier+ img_emb1, # the vector. list or np.array+ {"type": "jpg"} # associated metadata+ ), (+ "two.jpg",+ img_emb2,+ {"type": "jpg"}+ ), (+ "three.jpg",+ img_emb3,+ {"type": "jpg"}+ ), (+ "four.jpg",+ img_emb4,+ {"type": "jpg"}+ )+ ]+ )+ print("Inserted images")++ # index the collection for fast search performance+ images.create_index()+ print("Created index")+```++Add his method as a script in your `pyproject.toml` file:++```toml+[tool.poetry.scripts]+start = "image_search.main:start"+seed = "image_search.main:seed"+```++Afer activating the virtual environtment with `poetry shell` you can now run your seed script via `poetry run seed`. You can inspect the generated embeddings in your local Database by visiting the local Supabase Dasbboard at [localhost:54323](http://localhost:54323/project/default/editor), selecting the `vecs` schema, and the `image_vectors` database.++## Perform an Image Search from a Text Query++With Supabase Vector we can easily query our embeddings. We can use either an image as search input or alternative we can generate an embedding from a string input and use that as the query input:++```python+def start():+ # create vector store client+ vx = vecs.create_client(DB_CONNECTION)+ images = vx.get_collection(name="image_vectors")++ # Load CLIP model+ model = SentenceTransformer('clip-ViT-B-32')+ # Encode text query+ query_string = "a bike in front of a red brick wall"+ text_emb = model.encode(query_string)++ # query the collection filtering metadata for "type" = "jpg"+ results = images.query(+ query_vector=text_emb, # required+ limit=1, # number of records to return+ filters={"type": {"$eq": "jpg"}}, # metadata filters+ )+ result = results[0]+ print(result)+ plt.title(result)+ image = mpimg.imread('./images/' + result)+ plt.imshow(image)+ plt.show()+```++By limiting the query to one result, we can show the most relevant image result to the user. Finally we use `matplotlib` to show the image result to the user.++That's it, go ahead and test it out by running `poetry run start` and you will be presented with an image of a "bike in front of a red brick wall".++## Conclusion++With just a couple of lines of Python you are able to implement image search as well as reverse image search using OpenAI's CLIP model and Supabase Vector.++export const Page = ({ children }) => <Layout meta={meta} children={children} />++export default Page