Using ๐Ÿค— datasets for image search

Using the ๐Ÿค— datasets to make an image search engine for British Library Book Illustrations
Author

Daniel van Strien

Published

January 13, 2022

tl;dr itโ€™s really easy to use the huggingface datasets library to create an image search application but it might not be suitable for sharing. update an updated version of this post is on the ๐Ÿค— blog!

๐Ÿค— Datasets is a library for easily accessing and sharing datasets, and evaluation metrics for Natural Language Processing (NLP), computer vision, and audio tasks. source

When datasets was first launched it was more usually associated with text data and nlp. However, datasets has got support for images. In particular there is now a datasets feature type for images{% fn %}. In this blog post I try and play around with this new datatype, in combination with some other nice features of the library to make an image search app.

To start lets take a look at the image feature. We can use the wonderful rich libary to poke around python objects (functions, classes etc.)

from rich import inspect
from datasets.features import features
inspect(features.Image, help=True)
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ <class 'datasets.features.image.Image'> โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ def Image(id: Union[str, NoneType] = None) -> None:                              โ”‚
โ”‚                                                                                  โ”‚
โ”‚ Image feature to read image data from an image file.                             โ”‚
โ”‚                                                                                  โ”‚
โ”‚ Input: The Image feature accepts as input:                                       โ”‚
โ”‚ - A :obj:`str`: Absolute path to the image file (i.e. random access is allowed). โ”‚
โ”‚ - A :obj:`dict` with the keys:                                                   โ”‚
โ”‚                                                                                  โ”‚
โ”‚     - path: String with relative path of the image file to the archive file.     โ”‚
โ”‚     - bytes: Bytes of the image file.                                            โ”‚
โ”‚                                                                                  โ”‚
โ”‚   This is useful for archived files with sequential access.                      โ”‚
โ”‚                                                                                  โ”‚
โ”‚ - An :obj:`np.ndarray`: NumPy array representing an image.                       โ”‚
โ”‚ - A :obj:`PIL.Image.Image`: PIL image object.                                    โ”‚
โ”‚                                                                                  โ”‚
โ”‚   dtype = 'dict'                                                                 โ”‚
โ”‚      id = None                                                                   โ”‚
โ”‚ pa_type = None                                                                   โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

We can see there a few different ways in which we can pass in our images. Weโ€™ll come back to this in a little while.

A really nice feature of the datasets library (beyond the functionality for processing data, memory mapping etc.) is that you get some nice things for free. One of these is the ability to add a faiss index. faiss is a โ€œlibrary for efficient similarity search and clustering of dense vectorsโ€.

The datasets docs show and example of using faiss for text retrieval. What Iโ€™m curious about doing is using the faiss index to search for images. This can be super useful for a number of reasons but also comes with some potential issues.

The dataset: โ€œDigitised Books - Images identified as Embellishments. c. 1510 - c. 1900. JPGโ€

This is a dataset of images which have been pulled from a collection of digitised books from the British Library. These images come from books across a wide time period and from a broad range of domains. These images were extracted using information in the OCR output for each book. As a result itโ€™s known which book the images came from but not necessarily anything else about that image i.e. what it is of.

Some attempts to help overcome this have included uploading the images to flickr. This allows people to tag the images or put them into various different categories.

There have also been projects to tag the dataset using machine learning. This work already makes it possible to search by tags but we might want a โ€˜richerโ€™ ability to search. For this particular experiment I will work with a subset of the collections which contain โ€œembellishmentsโ€. This dataset is a bit smaller so will be better for experimenting with. We can get the data from the BL repository: https://doi.org/10.21250/db17

# hide_output
!aria2c -x8 -o dig19cbooks-embellishments.zip "https://bl.iro.bl.uk/downloads/ba1d1d12-b1bd-4a43-9696-7b29b56cdd20?locale=en"

01/12 20:18:42 [NOTICE] Downloading 1 item(s)

01/12 20:18:42 [NOTICE] Removed the defunct control file /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip.aria2 because the download file /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip doesn't exist.

01/12 20:18:42 [NOTICE] Allocating disk space. Use --file-allocation=none to disable it. See --file-allocation option in man page for more details.
 *** Download Progress Summary as of Wed Jan 12 20:19:43 2022 ***              58s](98%)]m
===============================================================================
[#f38a5d 553MiB/43GiB(1%) CN:5 DL:36MiB ETA:19m55s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:20:44 2022 ***              46s]
===============================================================================
[#f38a5d 2.6GiB/43GiB(6%) CN:5 DL:37MiB ETA:18m38s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:21:45 2022 ***              m1s]m
===============================================================================
[#f38a5d 4.7GiB/43GiB(10%) CN:5 DL:36MiB ETA:18m8s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:22:45 2022 ***              m46s]
===============================================================================
[#f38a5d 6.7GiB/43GiB(15%) CN:5 DL:31MiB ETA:19m38s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:23:46 2022 ***              m23s]
===============================================================================
[#f38a5d 8.8GiB/43GiB(20%) CN:5 DL:35MiB ETA:16m42s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:24:46 2022 ***              2s]mm
===============================================================================
[#f38a5d 10GiB/43GiB(24%) CN:5 DL:28MiB ETA:19m59s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:25:47 2022 ***              28s]
===============================================================================
[#f38a5d 12GiB/43GiB(29%) CN:5 DL:36MiB ETA:14m19s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:26:47 2022 ***              43s]
===============================================================================
[#f38a5d 14GiB/43GiB(33%) CN:5 DL:35MiB ETA:13m57s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:27:48 2022 ***              36s]
===============================================================================
[#f38a5d 16GiB/43GiB(37%) CN:5 DL:33MiB ETA:13m51s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:28:49 2022 ***              32s]
===============================================================================
[#f38a5d 18GiB/43GiB(42%) CN:5 DL:37MiB ETA:11m31s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:29:49 2022 ***              14s]
===============================================================================
[#f38a5d 20GiB/43GiB(46%) CN:5 DL:32MiB ETA:12m2s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:30:50 2022 ***              6s]m
===============================================================================
[#f38a5d 22GiB/43GiB(51%) CN:5 DL:36MiB ETA:9m55s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:31:51 2022 ***              9s]m
===============================================================================
[#f38a5d 24GiB/43GiB(56%) CN:5 DL:37MiB ETA:8m38s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:32:51 2022 ***              4s]
===============================================================================
[#f38a5d 26GiB/43GiB(61%) CN:5 DL:36MiB ETA:7m43s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:33:52 2022 ***              0s]
===============================================================================
[#f38a5d 28GiB/43GiB(66%) CN:5 DL:37MiB ETA:6m38s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:34:52 2022 ***              8s]
===============================================================================
[#f38a5d 31GiB/43GiB(71%) CN:5 DL:36MiB ETA:5m47s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:35:53 2022 ***              s]m
===============================================================================
[#f38a5d 32GiB/43GiB(75%) CN:5 DL:17MiB ETA:10m7s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:36:53 2022 ***              1s]m
===============================================================================
[#f38a5d 34GiB/43GiB(79%) CN:5 DL:27MiB ETA:5m31s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:37:54 2022 ***              4s]
===============================================================================
[#f38a5d 35GiB/43GiB(82%) CN:5 DL:29MiB ETA:4m22s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:38:55 2022 ***              5s]
===============================================================================
[#f38a5d 37GiB/43GiB(86%) CN:5 DL:26MiB ETA:3m36s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:39:55 2022 ***              5s]
===============================================================================
[#f38a5d 39GiB/43GiB(91%) CN:5 DL:36MiB ETA:1m44s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

 *** Download Progress Summary as of Wed Jan 12 20:40:56 2022 ***              ]mm
===============================================================================
[#f38a5d 41GiB/43GiB(95%) CN:5 DL:34MiB ETA:52s]
FILE: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip
-------------------------------------------------------------------------------

[#f38a5d 43GiB/43GiB(99%) CN:2 DL:35MiB]0m]m
01/12 20:41:49 [NOTICE] Download complete: /Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip

Download Results:
gid   |stat|avg speed  |path/URI
======+====+===========+=======================================================
f38a5d|OK  |    33MiB/s|/Users/dvanstrien/Documents/daniel/blog/_notebooks/dig19cbooks-embellishments.zip

Status Legend:
(OK):download completed.
!unzip -q dig19cbooks-embellishments.zip

Install required packages

There are a few packages weโ€™ll need for this work. To start with weโ€™ll need the datasets library.

# hide output
import sys
!{sys.executable} -m pip install datasets 

Now we have the data downloaded weโ€™ll try and load it into datasets. There are various ways of doing this. To start with we can grab all of the files we need.

from pathlib import Path
files = list(Path('embellishments/').rglob("*.jpg"))

Since the file path encodes the year of publication for the book the image came from letโ€™s create a function to grab that.

def get_parts(f:Path):
    _,year,fname =  f.parts
    return year, fname

๐Ÿ“ธ Loading the images

The images are fairly large, since this is an experiment weโ€™ll resize them a little using the thumbnail method (this makes sure we keep the same aspect ratio for our images)

from PIL import Image
import io
def load_image(path):
    with open(path, 'rb') as f:
        im = Image.open(io.BytesIO(f.read()))
        im.thumbnail((224,224))
    return im 
im = load_image(files[0])
im

Where is the image ๐Ÿค”

You may have noticed that the load_image function doesnโ€™t load the filepath into pillow directly. Often we would do Image.open(filepath.jpg). This is done deliberately. If we load it this way when we inspect the resulting image youโ€™ll see that the filepath attribute is empty.

#collapse_output
inspect(im)
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ <class 'PIL.JpegImagePlugin.JpegImageFile'> โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚
โ”‚ โ”‚ <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x224 at 0x7FBBB392D040>     โ”‚ โ”‚
โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚
โ”‚                                                                                           โ”‚
โ”‚                app = {'APP0': b'JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00'}            โ”‚
โ”‚            applist = [('APP0', b'JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00')]          โ”‚
โ”‚               bits = 8                                                                    โ”‚
โ”‚    custom_mimetype = None                                                                 โ”‚
โ”‚      decoderconfig = (2, 0)                                                               โ”‚
โ”‚    decodermaxblock = 65536                                                                โ”‚
โ”‚      encoderconfig = (False, -1, -1, b'')                                                 โ”‚
โ”‚        encoderinfo = {}                                                                   โ”‚
โ”‚           filename = ''                                                                   โ”‚
โ”‚             format = 'JPEG'                                                               โ”‚
โ”‚ format_description = 'JPEG (ISO 10918)'                                                   โ”‚
โ”‚                 fp = None                                                                 โ”‚
โ”‚             height = 224                                                                  โ”‚
โ”‚         huffman_ac = {}                                                                   โ”‚
โ”‚         huffman_dc = {}                                                                   โ”‚
โ”‚            icclist = []                                                                   โ”‚
โ”‚                 im = <ImagingCore object at 0x7fbba120dc10>                               โ”‚
โ”‚               info = {                                                                    โ”‚
โ”‚                          'jfif': 257,                                                     โ”‚
โ”‚                          'jfif_version': (1, 1),                                          โ”‚
โ”‚                          'jfif_unit': 0,                                                  โ”‚
โ”‚                          'jfif_density': (1, 1)                                           โ”‚
โ”‚                      }                                                                    โ”‚
โ”‚              layer = [(1, 2, 2, 0), (2, 1, 1, 1), (3, 1, 1, 1)]                           โ”‚
โ”‚             layers = 3                                                                    โ”‚
โ”‚                map = None                                                                 โ”‚
โ”‚               mode = 'RGB'                                                                โ”‚
โ”‚            palette = None                                                                 โ”‚
โ”‚           pyaccess = None                                                                 โ”‚
โ”‚       quantization = {                                                                    โ”‚
โ”‚                          0: [                                                             โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              1,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              6,                                                           โ”‚
โ”‚                              7,                                                           โ”‚
โ”‚                              9,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              4,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              6,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              10,                                                          โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              4,                                                           โ”‚
โ”‚                              7,                                                           โ”‚
โ”‚                              12,                                                          โ”‚
โ”‚                              11,                                                          โ”‚
โ”‚                              9,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              5,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              10,                                                          โ”‚
โ”‚                              15,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              11,                                                          โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              5,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              9,                                                           โ”‚
โ”‚                              11,                                                          โ”‚
โ”‚                              15,                                                          โ”‚
โ”‚                              16,                                                          โ”‚
โ”‚                              13,                                                          โ”‚
โ”‚                              7,                                                           โ”‚
โ”‚                              9,                                                           โ”‚
โ”‚                              11,                                                          โ”‚
โ”‚                              12,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              17,                                                          โ”‚
โ”‚                              17,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              10,                                                          โ”‚
โ”‚                              13,                                                          โ”‚
โ”‚                              13,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              16,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14                                                           โ”‚
โ”‚                          ],                                                               โ”‚
โ”‚                          1: [                                                             โ”‚
โ”‚                              2,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              7,                                                           โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              4,                                                           โ”‚
โ”‚                              9,                                                           โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              3,                                                           โ”‚
โ”‚                              4,                                                           โ”‚
โ”‚                              8,                                                           โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              7,                                                           โ”‚
โ”‚                              9,                                                           โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14,                                                          โ”‚
โ”‚                              14                                                           โ”‚
โ”‚                          ]                                                                โ”‚
โ”‚                      }                                                                    โ”‚
โ”‚           readonly = 0                                                                    โ”‚
โ”‚               size = (200, 224)                                                           โ”‚
โ”‚               tile = []                                                                   โ”‚
โ”‚              width = 200                                                                  โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

You can also directly see this

im.filename
''

Pillow usually loads images in a lazy way i.e. it only opens them when they are needed. The filepath is used to access the image. We can see the filename attribute is present if we open it from the filepath

im_file = Image.open(files[0])
im_file.filename
'/Users/dvanstrien/Documents/daniel/blog/_notebooks/embellishments/1855/000811462_05_000205_1_The Pictorial History of England  being a history of the people  as well as a hi_1855.jpg'

The reason I donโ€™t want the filename attribute present here is because not only do I want to use datasets to process our images but also store the images. If we pass a Pillow object with the filename attribute datasets will also use this for loading the images. This is often what weโ€™d want but we donโ€™t want this here for reasons weโ€™ll see shortly.

Preparing images for datasets

We can now load our images. What weโ€™ll do is is loop through all our images and then load the information for each image into a dictionary.

from collections import defaultdict
data = defaultdict(list)
from tqdm import tqdm
for file in tqdm(files):
    try:
        #load_image(file)
        year, fname = get_parts(file)
        data['fname'].append(fname)
        data['year'].append(year)
        data['path'].append(str(file))
    except:
        Image.UnidentifiedImageError
        pass
        
100%|โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 416944/416944 [00:05<00:00, 77169.45it/s]

We can now load the from_dict method to create a new dataset.

from datasets import Dataset
dataset = Dataset.from_dict(data)

We can look at one example to see what this looks like.

dataset[0]
{'fname': '000811462_05_000205_1_The Pictorial History of England  being a history of the people  as well as a hi_1855.jpg',
 'year': '1855',
 'path': 'embellishments/1855/000811462_05_000205_1_The Pictorial History of England  being a history of the people  as well as a hi_1855.jpg'}

Loading our images

At the moment our dataset has the filename and full path for each image. However, we want to have an actual image loaded into our dataset. We already have a load_image function. This gets us most of the way there but we might also want to add some ability to deal with image errors. The datasets library has gained increased uspport for handling None types- this includes support for None types for images see pull request 3195.

Weโ€™ll wrap our load_image function in a try block, catch a Image.UnidentifiedImageError error and return None if we canโ€™t load the image.

def try_load_image(filename):
    try:
        image = load_image(filename)
        if isinstance(image, Image.Image):
            return image
    except Image.UnidentifiedImageError:
        return None
%%time
dataset = dataset.map(lambda example: {"img": try_load_image(example['path'])},writer_batch_size=50)
CPU times: user 51min 42s, sys: 4min 31s, total: 56min 13s
Wall time: 1h 10min 31s

Letโ€™s see what this looks like

dataset
Dataset({
    features: ['fname', 'year', 'path', 'img'],
    num_rows: 416944
})

We have an image column, letโ€™s check the type of all our features

dataset.features
{'fname': Value(dtype='string', id=None),
 'year': Value(dtype='string', id=None),
 'path': Value(dtype='string', id=None),
 'img': Image(id=None)}

This is looking great already. Since we might have some None types for images letโ€™s get rid of these.

dataset = dataset.filter(lambda example: example['img'] is not None)
dataset
Dataset({
    features: ['fname', 'year', 'path', 'img'],
    num_rows: 416935
})

Youโ€™ll see we lost a few rows by doing this filtering. We should now just have images which are successfully loaded.

If we access an example and index into the img column weโ€™ll see our image ๐Ÿ˜ƒ

dataset[10]['img']

Push all the things to the hub!

Push all the things to the hub!

One of the super awesome things about the huggingface ecosystem is the huggingface hub. We can use the hub to access models and datasets. Often this is used for sharing work with others but it can also be a useful tool for work in progress. The datasets library recently added a push_to_hub method that allows you to push a dataset to the hub with minimal fuss. This can be really helpful by allowing you to pass around a dataset with all the transformers etc. already done.

When I started playing around with this feature I was also keen to see if it could be used as a way of โ€˜bundlingโ€™ everything together. This is where I noticed that if you push a dataset containing images which have been loaded in from filepaths by pillow the version on the hub wonโ€™t have the images attached. If you always have the image files in the same place when you work with the dataset then this doesnโ€™t matter. If you want to have the images stored in the parquet file(s) associated with the dataset we need to load it without the filename attribute present (there might be another way of ensuring that datasets doesnโ€™t rely on the image file being on the file system โ€“ if you of this Iโ€™d love to hear about it).

Since we loaded our images this way when we download the dataset from the hub onto a different machine we have the images already there ๐Ÿค—

For now weโ€™ll push the dataset to the hub and keep them private initially.

dataset.push_to_hub('davanstrien/embellishments', private=True)
The repository already exists: the `private` keyword argument will be ignored.

Switching machines

At this point Iโ€™ve created a dataset and moved it to the huggingface hub. This means it is possible to pickup the work/dataset elsewhere.

In this particular example, having access to a GPU is important. So the next parts of this notebook are run on Colab instead of locally on my laptop.

Weโ€™ll need to login since the dataset is currently private.

!huggingface-cli login

        _|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|
        _|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|
        _|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|
        _|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|
        _|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|

        To login, `huggingface_hub` now requires a token generated from https://huggingface.co/settings/token.
        (Deprecated, will be removed in v0.3.0) To login with username and password instead, interrupt with Ctrl+C.
        
Token: 
Login successful
Your token has been saved to /root/.huggingface/token
Authenticated through git-credential store but this isn't the helper defined on your machine.
You might have to re-authenticate when pushing to the Hugging Face Hub. Run the following command in your terminal in case you want to set this credential helper as the default

git config --global credential.helper store

Once weโ€™ve done this we can load our dataset

from datasets import load_dataset

dataset = load_dataset("davanstrien/embellishments", use_auth_token=True)
Using custom data configuration davanstrien--embellishments-543da8e15e8f0242
Downloading and preparing dataset None/None (download: 2.38 GiB, generated: 2.50 GiB, post-processed: Unknown size, total: 4.88 GiB) to /root/.cache/huggingface/datasets/parquet/davanstrien--embellishments-543da8e15e8f0242/0.0.0/1638526fd0e8d960534e2155dc54fdff8dce73851f21f031d2fb9c2cf757c121...
Dataset parquet downloaded and prepared to /root/.cache/huggingface/datasets/parquet/davanstrien--embellishments-543da8e15e8f0242/0.0.0/1638526fd0e8d960534e2155dc54fdff8dce73851f21f031d2fb9c2cf757c121. Subsequent calls will reuse this data.

Creating embeddings ๐Ÿ•ธ

We now have a dataset with a bunch of images in it. To begin creating our image search app we need to create some embeddings for these images. There are various ways in which we can try and do this but one possible way is to use the clip models via the sentence_transformers library. The clip model from OpenAI learns a joint representation for both images and text which is very useful for what we want to do since we want to be able to input text and get back an image. We can download the model using the SentenceTransformer class.

from sentence_transformers import SentenceTransformer, util

model = SentenceTransformer('clip-ViT-B-32')
ftfy or spacy is not installed using BERT BasicTokenizer instead of ftfy.

This model will encode either an image or some text returning an embedding. We can use the map method to encode all our images.

ds_with_embeddings = dataset.map(
    lambda example: {'embeddings':model.encode(example['img'],device='cuda')},
                                 batch_size=32)

We can โ€œsaveโ€ our work by pushing back to the hub

ds_with_embeddings.push_to_hub('davanstrien/embellishments', private=True)
Pushing split train to the Hub.
The repository already exists: the `private` keyword argument will be ignored.

If we were to move to a different machine we could grab our work again by loading it from the hub ๐Ÿ˜ƒ

from datasets import load_dataset

ds_with_embeddings = load_dataset("davanstrien/embellishments", use_auth_token=True)
Using custom data configuration davanstrien--embellishments-c2c1f142f272db02
Downloading and preparing dataset None/None (download: 3.19 GiB, generated: 3.30 GiB, post-processed: Unknown size, total: 6.49 GiB) to /root/.cache/huggingface/datasets/parquet/davanstrien--embellishments-c2c1f142f272db02/0.0.0/1638526fd0e8d960534e2155dc54fdff8dce73851f21f031d2fb9c2cf757c121...
Dataset parquet downloaded and prepared to /root/.cache/huggingface/datasets/parquet/davanstrien--embellishments-c2c1f142f272db02/0.0.0/1638526fd0e8d960534e2155dc54fdff8dce73851f21f031d2fb9c2cf757c121. Subsequent calls will reuse this data.

We now have a new column which contains the embeddings for our images. We could manually search through these and compare it to some input embedding but datasets has an add_faiss_index method. This uses the faiss library to create an efficient index for searching embeddings. For more background on this library you can watch this youtube video

ds_with_embeddings['train'].add_faiss_index(column='embeddings')
Dataset({
    features: ['fname', 'year', 'path', 'img', 'embeddings'],
    num_rows: 416935
})

Creating a huggingface space? ๐Ÿคท๐Ÿผ

One obvious next step for this kind of project is to create a hugginface spaces demo. This is what Iโ€™ve done for other models

It was a fairly simple process to get a Gradio app setup from the point we got to here. Here is a screenshot of this app.

However, Iโ€™m a little bit vary about making this public straightaway. Looking at the model card for the CLIP model we can look at the primary intended uses:

Primary intended uses

We primarily imagine the model will be used by researchers to better understand robustness, generalization, and other capabilities, biases, and constraints of computer vision models. source

This is fairly close to what we are interested in here. Particularly we might be interested in how well the model deals with the kinds of images in our dataset (illustrations from mostly 19th century books). The images in our dataset are (probably) fairly different from the training data. The fact that some of the images also contain text might help CLIP since it displays some OCR ability.

However, looking at the out-of-scope use cases in the model card:

Out-of-Scope Use Cases

Any deployed use case of the model - whether commercial or not - is currently out of scope. Non-deployed use cases such as image search in a constrained environment, are also not recommended unless there is thorough in-domain testing of the model with a specific, fixed class taxonomy. This is because our safety assessment demonstrated a high need for task specific testing especially given the variability of CLIPโ€™s performance with different class taxonomies. This makes untested and unconstrained deployment of the model in any use case currently potentially harmful. source

suggests that โ€˜deploymentโ€™ is not a good idea. Whilst the results I got are interesting I havenโ€™t played around with the model enough yet (and havenโ€™t done anything more systematic to evaluate its performance and biases). Another additional consideration is the target dataset itself. The images are drawn from books covering a variety of subjects and time periods. There are plenty of books which represent colonial attitudes and as a result some of the images included may represent certain groups of people in a negative way. This could potentially be a bad combo with a tool which allows any arbitrary text input to be encoded as a prompt.

There may be ways around this issue but this will require a bit more thought.

Conclusion

Although I donโ€™t have a nice demo to show for it I did get to work out a few more details of how datasets handles images. Iโ€™ve already used it to train some classification models and everything seems to be working smoothly. The ability to push images around on the hub will be super useful for many use cases too.

I plan to spend a bit more time thinking about whether there is a better way of sharing a clip powered image search for the BL book images or notโ€ฆ

{{ โ€œIf you arenโ€™t familiar with datasets. A feature represents the datatype for different data you can have inside a dataset. For example you my have int32, timestamps and strings. You can read more about how features work in the docsโ€ | fndetail: 1}}