Datachain

ImageFile

ImageFile is inherited from File with additional methods for working with image files.

ImageFile is generated when a DataChain is created from storage, using type="image" param:

import datachain as dc

chain = dc.read_storage("s3://bucket-name/", type="image")

ImageFile

ImageFile(**kwargs)

Bases: File

DataModel for reading image files.

Source code in datachain/lib/file.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def __init__(self, **kwargs):
    super().__init__(**kwargs)
    # Annotations only: in the class body the pydantic mypy plugin would take
    # them for fields.
    self._caching_enabled: bool
    self._download_cb: Callback
    self._fs_path_cache: tuple[str, str, str] | None
    # The runtime state, set in one __dict__ update: pydantic's __setattr__ per
    # attribute is slow when millions of Files are built. A subclass that
    # declares them as private attributes needs pydantic's setattr instead.
    if _FILE_STATE.keys() & self.__private_attributes__.keys():
        for name, value in _FILE_STATE.items():
            setattr(self, name, value)
    else:
        self.__dict__.update(_FILE_STATE)

get_info

get_info() -> Image

Retrieves metadata and information about the image file.

Reuses cached content when available without populating the cache. Use .settings(prefetch=0) for metadata-only chains to avoid downloading files in advance.

Returns:

  • Image ( Image ) –

    A Model containing image metadata such as width, height and format.

Source code in datachain/lib/file.py
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
def get_info(self) -> "Image":
    """
    Retrieves metadata and information about the image file.

    Reuses cached content when available without populating the cache.
    Use `.settings(prefetch=0)` for metadata-only chains to avoid downloading
    files in advance.

    Returns:
        Image: A Model containing image metadata such as width, height and format.
    """
    from .image import image_info

    return image_info(self)

read

read()

Returns PIL.Image.Image object.

Source code in datachain/lib/file.py
1359
1360
1361
1362
1363
1364
def read(self):
    """Returns `PIL.Image.Image` object."""
    from PIL import Image as PilImage

    fobj = super().read()
    return PilImage.open(BytesIO(fobj))

save

save(destination: str, format: str | None = None, client_config: dict | None = None, *, content_type: str | None = None, content_disposition: str | None = None, cache_control: str | None = None, content_encoding: str | None = None, metadata: dict[str, str] | None = None, write_options: dict[str, Any] | None = None) -> ImageFile

Save the image to destination, optionally re-encoding to format.

If destination is a remote path, the image will be uploaded to remote storage. See :meth:File.save for full destination semantics and the object-metadata keyword arguments.

Source code in datachain/lib/file.py
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
def save(  # type: ignore[override]
    self,
    destination: str,
    format: str | None = None,
    client_config: dict | None = None,
    *,
    content_type: str | None = None,
    content_disposition: str | None = None,
    cache_control: str | None = None,
    content_encoding: str | None = None,
    metadata: dict[str, str] | None = None,
    write_options: dict[str, Any] | None = None,
) -> "ImageFile":
    """Save the image to *destination*, optionally re-encoding to *format*.

    If ``destination`` is a remote path, the image will be uploaded to
    remote storage.  See :meth:`File.save` for full destination semantics
    and the object-metadata keyword arguments.
    """
    if self._catalog is None:
        raise RuntimeError("Cannot save file: catalog is not set")
    destination = stringify_path(destination)

    # If format is not provided, determine it from the file extension
    if format is None:
        from pathlib import PurePosixPath

        from PIL import Image as PilImage

        ext = PurePosixPath(destination).suffix.lower()
        format = PilImage.registered_extensions().get(ext)

    if not format:
        raise FileError(
            f"Can't determine format for destination '{destination}'",
            self.source,
            self.path,
        )

    buf = BytesIO()
    self.read().save(buf, format=format)
    client, rel_path = self._resolve_destination(destination, client_config)
    result = client.upload(
        buf.getvalue(),
        rel_path,
        write_config=WriteConfig(
            content_type=content_type,
            content_disposition=content_disposition,
            cache_control=cache_control,
            content_encoding=content_encoding,
            metadata=metadata,
            write_options=write_options,
        ),
    )
    img = ImageFile(**result.model_dump())
    img._set_stream(self._catalog)
    return img

Image

Bases: DataModel

A data model representing metadata for an image file.

Attributes:

  • width (int) –

    The width of the image in pixels. Defaults to -1 if unknown.

  • height (int) –

    The height of the image in pixels. Defaults to -1 if unknown.

  • format (str) –

    The format of the image file (e.g., 'jpg', 'png'). Defaults to an empty string.