File size: 7,203 Bytes
2743dd0
 
 
 
 
 
 
 
 
 
 
 
 
f06d2fd
 
2743dd0
 
f06d2fd
 
 
2743dd0
f06d2fd
 
 
 
2743dd0
 
f06d2fd
2743dd0
 
f06d2fd
2743dd0
f06d2fd
2743dd0
f06d2fd
 
 
 
 
 
2743dd0
f06d2fd
2743dd0
 
f06d2fd
2743dd0
f06d2fd
2743dd0
f06d2fd
2743dd0
 
f06d2fd
 
2743dd0
 
 
f06d2fd
2743dd0
 
 
f06d2fd
 
2743dd0
 
 
 
 
 
 
 
f06d2fd
2743dd0
 
 
f06d2fd
 
 
2743dd0
 
 
 
 
 
 
 
 
 
 
 
 
f06d2fd
 
 
2743dd0
 
 
f06d2fd
2743dd0
 
f06d2fd
 
 
2743dd0
 
f06d2fd
 
2743dd0
 
 
 
 
f06d2fd
 
2743dd0
 
 
f06d2fd
 
 
 
 
2743dd0
f06d2fd
2743dd0
 
f06d2fd
2743dd0
 
f06d2fd
2743dd0
f06d2fd
 
 
 
 
2743dd0
 
 
 
 
 
 
 
 
f06d2fd
 
 
 
2743dd0
 
f06d2fd
2743dd0
 
f06d2fd
 
2743dd0
 
 
 
 
f06d2fd
2743dd0
 
 
f06d2fd
 
 
 
2743dd0
 
 
 
 
 
 
f06d2fd
 
 
2743dd0
 
 
f06d2fd
 
2743dd0
 
 
 
 
 
 
 
f06d2fd
2743dd0
 
 
 
 
 
f06d2fd
2743dd0
 
 
 
f06d2fd
 
 
2743dd0
f06d2fd
2743dd0
 
f06d2fd
2743dd0
f06d2fd
 
 
 
 
 
2743dd0
f06d2fd
2743dd0
 
f06d2fd
2743dd0
 
 
 
f06d2fd
 
2743dd0
 
 
 
 
 
 
f06d2fd
 
2743dd0
 
 
 
 
f06d2fd
2743dd0
 
f06d2fd
 
 
 
2743dd0
f06d2fd
2743dd0
 
 
 
f06d2fd
 
 
 
 
 
2743dd0
 
 
 
 
 
 
 
 
 
 
 
 
f06d2fd
 
 
2743dd0
 
 
 
f06d2fd
 
 
2743dd0
 
 
 
 
 
 
 
f06d2fd
 
 
 
 
2743dd0
 
 
f06d2fd
 
 
2743dd0
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "chromadb==1.0.4",
#     "datasets==3.5.0",
#     "marimo",
#     "matplotlib==3.10.1",
#     "numpy==2.2.4",
#     "open-clip-torch==2.32.0",
#     "pillow==11.1.0",
# ]
# ///

import marimo

__generated_with = "0.12.8"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    return (mo,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        # Multimodal Retrieval

        Chroma supports multimodal collections, i.e. collections which contain, and can be queried by, multiple modalities of data.

        This notebook shows an example of how to create and query a collection with both text and images, using Chroma's built-in features.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ## Dataset

        We us a small subset of the [coco object detection dataset](https://huggingface.co/datasets/detection-datasets/coco), hosted on HuggingFace.

        We download a small fraction of all the images in the dataset locally, and use it to create a multimodal collection.
        """
    )
    return


@app.cell
def _():
    import os

    from datasets import load_dataset
    from matplotlib import pyplot as plt
    return load_dataset, os


@app.cell
def _(load_dataset, mo):
    with mo.status.spinner(title="Loading dataset"):
        dataset = load_dataset(
            path="detection-datasets/coco",
            name="default",
            split="train",
            streaming=True,
        )

    N_IMAGES = 20
    return N_IMAGES, dataset


@app.cell
def _(N_IMAGES, dataset, mo, os):
    # Write the images to a folder
    IMAGE_FOLDER = "images"
    os.makedirs(IMAGE_FOLDER, exist_ok=True)
    i = 0
    all_images = []
    with mo.status.spinner(title="Loading images"):
        for row in dataset.take(N_IMAGES):
            image = row["image"]
            all_images.append(image)
            image.save(f"images/{i}.jpg")
            i += 1
    return IMAGE_FOLDER, all_images


@app.cell(hide_code=True)
def _(mo):
    img_width = mo.ui.slider(
        label="Image width", start=100, stop=300, step=10, debounce=True
    )
    img_width
    return (img_width,)


@app.cell(hide_code=True)
def _(all_images, img_width, mo):
    import io


    def as_image(src):
        img_byte_arr = io.BytesIO()
        src.save(img_byte_arr, format=src.format or "PNG")
        img_byte_arr.seek(0)
        return mo.image(img_byte_arr, width=img_width.value)


    mo.hstack(
        [as_image(_img) for _img in all_images[10:]],
        wrap=True,
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ## Ingesting multimodal data

        Chroma supports multimodal collections by referencing external URIs for data types other than text.
        All you have to do is specify a data loader when creating the collection, and then provide the URI for each entry.

        For this example, we are only adding images, though you can also add text.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Creating a multi-modal collection

        First we create the default Chroma client.
        """
    )
    return


@app.cell
def _():
    import chromadb

    client = chromadb.Client()
    return (client,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Next we specify an embedding function and a data loader.

        The built-in `OpenCLIPEmbeddingFunction` works with both text and image data. The `ImageLoader` is a simple data loader that loads images from a local directory.
        """
    )
    return


@app.cell
def _():
    from chromadb.utils.data_loaders import ImageLoader
    from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction

    embedding_function = OpenCLIPEmbeddingFunction()
    image_loader = ImageLoader()
    return embedding_function, image_loader


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""We create a collection with the embedding function and data loader.""")
    return


@app.cell
def _(IMAGE_FOLDER, client, embedding_function, image_loader, os):
    collection = client.create_collection(
        name="multimodal_collection",
        embedding_function=embedding_function,
        data_loader=image_loader,
        get_or_create=True,
    )

    # Get the uris to the images
    image_uris = sorted(
        [
            os.path.join(IMAGE_FOLDER, image_name)
            for image_name in os.listdir(IMAGE_FOLDER)
        ]
    )
    ids = [str(i) for i in range(len(image_uris))]

    collection.add(ids=ids, uris=image_uris)
    return (collection,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Adding multi-modal data

        We add image data to the collection using the image URIs. The data loader and embedding functions we specified earlier will ingest data from the provided URIs automatically.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ## Querying a multi-modal collection

        We can query the collection using text as normal, since the `OpenCLIPEmbeddingFunction` works with both text and images.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    query = mo.ui.text_area(label="Query with text", full_width=True).form(
        bordered=False
    )
    mo.vstack([query, mo.md("Try: *animal* or *vehicle*")])
    return (query,)


@app.cell
def _(collection, mo, query):
    mo.stop(not query.value)
    _retrieved = collection.query(
        query_texts=[query.value], include=["data"], n_results=3
    )

    [mo.image(img, height=200) for img in _retrieved["data"][0]]
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        /// admonition | One more thing!
        We can also query by images directly, by using the `query_images` field in the `collection.query` method.
        ///
        """
    )
    return


@app.cell
def _(collection, mo, selected_image):
    mo.stop(not selected_image.value)
    import numpy as np
    from PIL import Image

    query_image = np.array(Image.open(selected_image.path()))
    selected = mo.as_html(mo.image(query_image))

    _retrieved = collection.query(
        query_images=[query_image], include=["data"], n_results=5
    )
    results = [mo.image(_img) for _img in _retrieved["data"][0][1:]]
    return results, selected


@app.cell(hide_code=True)
def _(IMAGE_FOLDER, mo):
    selected_image = mo.ui.file_browser(IMAGE_FOLDER, multiple=False)
    selected_image
    return (selected_image,)


@app.cell(hide_code=True)
def _(mo, results, selected):
    mo.hstack(
        [
            mo.vstack([mo.md("## Selected"), selected]),
            mo.vstack([mo.md("## Similar"), *results]),
        ],
        widths="equal",
        gap=4,
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""This example was adapted from [multimodal_retrieval.ipynb](https://github.com/chroma-core/chroma/blob/main/examples/multimodal/multimodal_retrieval.ipynb), using `marimo convert`.""")
    return


if __name__ == "__main__":
    app.run()