image_feature_extraction.py 4.6 KB

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