image_feature_extraction.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. from typing import Any, Union
  2. from ..utils import add_end_docstrings, is_vision_available
  3. from .base import GenericTensor, Pipeline, build_pipeline_init_args
  4. if is_vision_available():
  5. from PIL import Image
  6. from ..image_utils import load_image
  7. @add_end_docstrings(
  8. build_pipeline_init_args(has_image_processor=True),
  9. """
  10. image_processor_kwargs (`dict`, *optional*):
  11. Additional dictionary of keyword arguments passed along to the image processor e.g.
  12. {"size": {"height": 100, "width": 100}}
  13. pool (`bool`, *optional*, defaults to `False`):
  14. Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.
  15. """,
  16. )
  17. class ImageFeatureExtractionPipeline(Pipeline):
  18. """
  19. Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
  20. transformer, which can be used as features in downstream tasks.
  21. Example:
  22. ```python
  23. >>> from transformers import pipeline
  24. >>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction")
  25. >>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True)
  26. >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input image.
  27. torch.Size([1, 197, 768])
  28. ```
  29. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  30. This image feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
  31. `"image-feature-extraction"`.
  32. All vision models may be used for this pipeline. See a list of all models, including community-contributed models on
  33. [huggingface.co/models](https://huggingface.co/models).
  34. """
  35. _load_processor = False
  36. _load_image_processor = True
  37. _load_feature_extractor = False
  38. _load_tokenizer = False
  39. def _sanitize_parameters(self, image_processor_kwargs=None, return_tensors=None, pool=None, **kwargs):
  40. preprocess_params = {} if image_processor_kwargs is None else image_processor_kwargs
  41. postprocess_params = {}
  42. if pool is not None:
  43. postprocess_params["pool"] = pool
  44. if return_tensors is not None:
  45. postprocess_params["return_tensors"] = return_tensors
  46. if "timeout" in kwargs:
  47. preprocess_params["timeout"] = kwargs["timeout"]
  48. return preprocess_params, {}, postprocess_params
  49. def preprocess(self, image, timeout=None, **image_processor_kwargs) -> dict[str, GenericTensor]:
  50. image = load_image(image, timeout=timeout)
  51. model_inputs = self.image_processor(image, return_tensors="pt", **image_processor_kwargs)
  52. model_inputs = model_inputs.to(self.dtype)
  53. return model_inputs
  54. def _forward(self, model_inputs):
  55. model_outputs = self.model(**model_inputs)
  56. return model_outputs
  57. def postprocess(self, model_outputs, pool=None, return_tensors=False):
  58. pool = pool if pool is not None else False
  59. if pool:
  60. if "pooler_output" not in model_outputs:
  61. raise ValueError(
  62. "No pooled output was returned. Make sure the model has a `pooler` layer when using the `pool` option."
  63. )
  64. outputs = model_outputs["pooler_output"]
  65. else:
  66. # [0] is the first available tensor, logits or last_hidden_state.
  67. outputs = model_outputs[0]
  68. if return_tensors:
  69. return outputs
  70. return outputs.tolist()
  71. def __call__(self, *args: Union[str, "Image.Image", list["Image.Image"], list[str]], **kwargs: Any) -> list[Any]:
  72. """
  73. Extract the features of the input(s).
  74. Args:
  75. images (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
  76. The pipeline handles three types of images:
  77. - A string containing a http link pointing to an image
  78. - A string containing a local path to an image
  79. - An image loaded in PIL directly
  80. The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
  81. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
  82. images.
  83. timeout (`float`, *optional*, defaults to None):
  84. The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and
  85. the call may block forever.
  86. Return:
  87. A nested list of `float`: The features computed by the model.
  88. """
  89. return super().__call__(*args, **kwargs)