zero_shot_image_classification.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import warnings
  2. from collections import UserDict
  3. from typing import List, Union
  4. from ..utils import (
  5. add_end_docstrings,
  6. is_tf_available,
  7. is_torch_available,
  8. is_vision_available,
  9. logging,
  10. requires_backends,
  11. )
  12. from .base import Pipeline, build_pipeline_init_args
  13. if is_vision_available():
  14. from PIL import Image
  15. from ..image_utils import load_image
  16. if is_torch_available():
  17. import torch
  18. from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
  19. if is_tf_available():
  20. from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
  21. from ..tf_utils import stable_softmax
  22. logger = logging.get_logger(__name__)
  23. @add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
  24. class ZeroShotImageClassificationPipeline(Pipeline):
  25. """
  26. Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you
  27. provide an image and a set of `candidate_labels`.
  28. Example:
  29. ```python
  30. >>> from transformers import pipeline
  31. >>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
  32. >>> classifier(
  33. ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
  34. ... candidate_labels=["animals", "humans", "landscape"],
  35. ... )
  36. [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]
  37. >>> classifier(
  38. ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
  39. ... candidate_labels=["black and white", "photorealist", "painting"],
  40. ... )
  41. [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]
  42. ```
  43. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  44. This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  45. `"zero-shot-image-classification"`.
  46. See the list of available models on
  47. [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification).
  48. """
  49. def __init__(self, **kwargs):
  50. super().__init__(**kwargs)
  51. requires_backends(self, "vision")
  52. self.check_model_type(
  53. TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
  54. if self.framework == "tf"
  55. else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
  56. )
  57. def __call__(self, image: Union[str, List[str], "Image", List["Image"]] = None, **kwargs):
  58. """
  59. Assign labels to the image(s) passed as inputs.
  60. Args:
  61. image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
  62. The pipeline handles three types of images:
  63. - A string containing a http link pointing to an image
  64. - A string containing a local path to an image
  65. - An image loaded in PIL directly
  66. candidate_labels (`List[str]`):
  67. The candidate labels for this image. They will be formatted using *hypothesis_template*.
  68. hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`):
  69. The format used in conjunction with *candidate_labels* to attempt the image classification by
  70. replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
  71. already formatted.
  72. Return:
  73. A list of dictionaries containing one entry per proposed label. Each dictionary contains the
  74. following keys:
  75. - **label** (`str`) -- One of the suggested *candidate_labels*.
  76. - **score** (`float`) -- The score attributed by the model to that label. It is a value between
  77. 0 and 1, computed as the `softmax` of `logits_per_image`.
  78. """
  79. # After deprecation of this is completed, remove the default `None` value for `image`
  80. if "images" in kwargs:
  81. image = kwargs.pop("images")
  82. if image is None:
  83. raise ValueError("Cannot call the zero-shot-image-classification pipeline without an images argument!")
  84. return super().__call__(image, **kwargs)
  85. def _sanitize_parameters(self, tokenizer_kwargs=None, **kwargs):
  86. preprocess_params = {}
  87. if "candidate_labels" in kwargs:
  88. preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
  89. if "timeout" in kwargs:
  90. warnings.warn(
  91. "The `timeout` argument is deprecated and will be removed in version 5 of Transformers", FutureWarning
  92. )
  93. preprocess_params["timeout"] = kwargs["timeout"]
  94. if "hypothesis_template" in kwargs:
  95. preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
  96. if tokenizer_kwargs is not None:
  97. warnings.warn(
  98. "The `tokenizer_kwargs` argument is deprecated and will be removed in version 5 of Transformers",
  99. FutureWarning,
  100. )
  101. preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs
  102. return preprocess_params, {}, {}
  103. def preprocess(
  104. self,
  105. image,
  106. candidate_labels=None,
  107. hypothesis_template="This is a photo of {}.",
  108. timeout=None,
  109. tokenizer_kwargs=None,
  110. ):
  111. if tokenizer_kwargs is None:
  112. tokenizer_kwargs = {}
  113. image = load_image(image, timeout=timeout)
  114. inputs = self.image_processor(images=[image], return_tensors=self.framework)
  115. if self.framework == "pt":
  116. inputs = inputs.to(self.torch_dtype)
  117. inputs["candidate_labels"] = candidate_labels
  118. sequences = [hypothesis_template.format(x) for x in candidate_labels]
  119. padding = "max_length" if self.model.config.model_type == "siglip" else True
  120. text_inputs = self.tokenizer(sequences, return_tensors=self.framework, padding=padding, **tokenizer_kwargs)
  121. inputs["text_inputs"] = [text_inputs]
  122. return inputs
  123. def _forward(self, model_inputs):
  124. candidate_labels = model_inputs.pop("candidate_labels")
  125. text_inputs = model_inputs.pop("text_inputs")
  126. if isinstance(text_inputs[0], UserDict):
  127. text_inputs = text_inputs[0]
  128. else:
  129. # Batching case.
  130. text_inputs = text_inputs[0][0]
  131. outputs = self.model(**text_inputs, **model_inputs)
  132. model_outputs = {
  133. "candidate_labels": candidate_labels,
  134. "logits": outputs.logits_per_image,
  135. }
  136. return model_outputs
  137. def postprocess(self, model_outputs):
  138. candidate_labels = model_outputs.pop("candidate_labels")
  139. logits = model_outputs["logits"][0]
  140. if self.framework == "pt" and self.model.config.model_type == "siglip":
  141. probs = torch.sigmoid(logits).squeeze(-1)
  142. scores = probs.tolist()
  143. if not isinstance(scores, list):
  144. scores = [scores]
  145. elif self.framework == "pt":
  146. probs = logits.softmax(dim=-1).squeeze(-1)
  147. scores = probs.tolist()
  148. if not isinstance(scores, list):
  149. scores = [scores]
  150. elif self.framework == "tf":
  151. probs = stable_softmax(logits, axis=-1)
  152. scores = probs.numpy().tolist()
  153. else:
  154. raise ValueError(f"Unsupported framework: {self.framework}")
  155. result = [
  156. {"score": score, "label": candidate_label}
  157. for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
  158. ]
  159. return result