






"""simple docstring"""





import numpy as np
import torch
from torch.utils.data import Dataset, IterableDataset

from ..utils.generic import ModelOutput






class      a						(					__snake_case		):






    def __init__(       self     :							List[Any]       ,						__SCREAMING_SNAKE_CASE     :							List[str]       ,						__SCREAMING_SNAKE_CASE     :							List[Any]       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]					)     ->		Optional[Any]:
      lowerCamelCase_         =						dataset
      lowerCamelCase_         =						process
      lowerCamelCase_         =						params






    def __len__(       self     :							int					)     ->		List[str]:
      return len(self.dataset					)






    def __getitem__(       self     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							Union[str, Any]					)     ->		Tuple:
      lowerCamelCase_         =						self.dataset[i]
      lowerCamelCase_         =						self.process(__SCREAMING_SNAKE_CASE       ,						**self.params					)
      return processed






class      a						(					__snake_case		):






    def __init__(       self     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							Optional[Any]       ,						__SCREAMING_SNAKE_CASE     :							List[Any]       ,						__SCREAMING_SNAKE_CASE     :							List[str]       ,						__SCREAMING_SNAKE_CASE     :							List[str]=None					)     ->		Tuple:
      lowerCamelCase_         =						loader
      lowerCamelCase_         =						infer
      lowerCamelCase_         =						params
      if loader_batch_size == 1:
        # Let's spare some time by deactivating altogether
        lowerCamelCase_         =						None
      lowerCamelCase_         =						loader_batch_size

      # Internal bookkeeping
      lowerCamelCase_         =						None
      lowerCamelCase_         =						None






    def __len__(       self     :							Any					)     ->		Union[str, Any]:
      return len(self.loader					)






    def __iter__(       self     :							str					)     ->		str:
      lowerCamelCase_         =						iter(self.loader					)
      return self






    def    UpperCamelCase       (       self     :							Dict					)     ->		Any:






      if isinstance(self._loader_batch_data       ,						torch.Tensor					):
        # Batch data is simple tensor, just fetch the slice
        lowerCamelCase_         =						self._loader_batch_data[self._loader_batch_index]
      else:
        # Batch data is assumed to be BaseModelOutput (or dict)
        lowerCamelCase_         =						{}
        for k, element in self._loader_batch_data.items():
          if isinstance(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					):
            # Convert ModelOutput to tuple first
            lowerCamelCase_         =						element.to_tuple()
            if isinstance(element[0]       ,						torch.Tensor					):
              lowerCamelCase_         =						tuple(el[self._loader_batch_index].unsqueeze(0					) for el in element					)
            elif isinstance(element[0]       ,						np.ndarray					):
              lowerCamelCase_         =						tuple(np.expand_dims(el[self._loader_batch_index]       ,						0					) for el in element					)
            continue
          if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					):
            # Those are stored as lists of tensors so need specific unbatching.
            if isinstance(element[0]       ,						torch.Tensor					):
              lowerCamelCase_         =						tuple(el[self._loader_batch_index].unsqueeze(0					) for el in element					)
            elif isinstance(element[0]       ,						np.ndarray					):
              lowerCamelCase_         =						tuple(np.expand_dims(el[self._loader_batch_index]       ,						0					) for el in element					)
            continue
          if element is None:
            # This can happen for optional data that get passed around
            lowerCamelCase_         =						None
          elif isinstance(element[self._loader_batch_index]       ,						torch.Tensor					):
            # Take correct batch data, but make it looked like batch_size=1
            # For compatibility with other methods within transformers

            lowerCamelCase_         =						element[self._loader_batch_index].unsqueeze(0					)
          elif isinstance(element[self._loader_batch_index]       ,						np.ndarray					):
            # Take correct batch data, but make it looked like batch_size=1
            # For compatibility with other methods within transformers
            lowerCamelCase_         =						np.expand_dims(element[self._loader_batch_index]       ,						0					)
          else:
            # This is typically a list, so no need to `unsqueeze`.
            lowerCamelCase_         =						element[self._loader_batch_index]
            # Recreate the element by reusing the original class to make it look
            # batch_size=1
        lowerCamelCase_         =						self._loader_batch_data.__class__(__SCREAMING_SNAKE_CASE					)
      self._loader_batch_index += 1
      return result






    def    UpperCamelCase       (       self     :							Any					)     ->		int:






      if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
        # We are currently unrolling a batch so we just need to return
        # the current item within a batch
        return self.loader_batch_item()

      # We're out of items within a batch
      lowerCamelCase_         =						next(self.iterator					)
      lowerCamelCase_         =						self.infer(__SCREAMING_SNAKE_CASE       ,						**self.params					)
      # We now have a batch of "inferred things".
      if self.loader_batch_size is not None:
        # Try to infer the size of the batch
        if isinstance(__SCREAMING_SNAKE_CASE       ,						torch.Tensor					):
          lowerCamelCase_         =						processed
        else:
          lowerCamelCase_         =						list(processed.keys()					)[0]
          lowerCamelCase_         =						processed[key]
        if isinstance(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					):
          lowerCamelCase_         =						len(__SCREAMING_SNAKE_CASE					)
        else:
          lowerCamelCase_         =						first_tensor.shape[0]
        if 0 < observed_batch_size < self.loader_batch_size:
          # could be last batch so we can't unroll as many
          # elements.
          lowerCamelCase_         =						observed_batch_size
        # Setting internal index to unwrap the batch
        lowerCamelCase_         =						processed
        lowerCamelCase_         =						0
        return self.loader_batch_item()
      else:
        # We're not unrolling batches
        return processed






class      a						(					__snake_case		):






    def __init__(       self     :							Tuple       ,						__SCREAMING_SNAKE_CASE     :							Any       ,						__SCREAMING_SNAKE_CASE     :							List[str]       ,						__SCREAMING_SNAKE_CASE     :							str       ,						__SCREAMING_SNAKE_CASE     :							List[str]=None					)     ->		str:
      super().__init__(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					)






    def __iter__(       self     :							Tuple					)     ->		Union[str, Any]:
      lowerCamelCase_         =						iter(self.loader					)
      lowerCamelCase_         =						None
      return self






    def    UpperCamelCase       (       self     :							Optional[int]					)     ->		List[Any]:






      if self.subiterator is None:
        lowerCamelCase_         =						self.infer(next(self.iterator					)       ,						**self.params					)
      try:
        # Try to return next item
        lowerCamelCase_         =						next(self.subiterator					)
      except StopIteration:
        # When a preprocess iterator ends, we can start lookig at the next item
        # ChunkIterator will keep feeding until ALL elements of iterator
        # all have created their subiterator and have been iterating against.
        #
        # Another way to look at it, is we're basically flattening lists of lists
        # into a single list, but with generators
        lowerCamelCase_         =						self.infer(next(self.iterator					)       ,						**self.params					)
        lowerCamelCase_         =						next(self.subiterator					)
      return processed






class      a						(					__snake_case		):






    def __iter__(       self     :							Tuple					)     ->		Optional[Any]:
      lowerCamelCase_         =						iter(self.loader					)
      return self






    def    UpperCamelCase       (       self     :							List[str]					)     ->		Tuple:
      lowerCamelCase_         =						False
      lowerCamelCase_         =						[]
      if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
        while self._loader_batch_index < self.loader_batch_size:
          lowerCamelCase_         =						self.loader_batch_item()
          lowerCamelCase_         =						item.pop('is_last'					)
          accumulator.append(__SCREAMING_SNAKE_CASE					)
          if is_last:
            return accumulator

      while not is_last:
        lowerCamelCase_         =						self.infer(next(self.iterator					)       ,						**self.params					)
        if self.loader_batch_size is not None:
          if isinstance(__SCREAMING_SNAKE_CASE       ,						torch.Tensor					):
            lowerCamelCase_         =						processed
          else:
            lowerCamelCase_         =						list(processed.keys()					)[0]
            lowerCamelCase_         =						processed[key]
          if isinstance(__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE					):
            lowerCamelCase_         =						len(__SCREAMING_SNAKE_CASE					)
          else:
            lowerCamelCase_         =						first_tensor.shape[0]
          if 0 < observed_batch_size < self.loader_batch_size:
            # could be last batch so we can't unroll as many
            # elements.
            lowerCamelCase_         =						observed_batch_size
          lowerCamelCase_         =						processed
          lowerCamelCase_         =						0
          while self._loader_batch_index < self.loader_batch_size:
            lowerCamelCase_         =						self.loader_batch_item()
            lowerCamelCase_         =						item.pop('is_last'					)
            accumulator.append(__SCREAMING_SNAKE_CASE					)
            if is_last:
              return accumulator
        else:
          lowerCamelCase_         =						processed
          lowerCamelCase_         =						item.pop('is_last'					)
          accumulator.append(__SCREAMING_SNAKE_CASE					)
      return accumulator






class      a						(					__snake_case		):






    def __init__(       self     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							Dataset       ,						__SCREAMING_SNAKE_CASE     :							str					)     ->		List[Any]:
      lowerCamelCase_         =						dataset
      lowerCamelCase_         =						key






    def __len__(       self     :							Optional[int]					)     ->		int:
      return len(self.dataset					)






    def __getitem__(       self     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							Optional[int]					)     ->		Optional[Any]:
      return self.dataset[i][self.key]






class      a						(					__snake_case		):






    def __init__(       self     :							List[Any]       ,						__SCREAMING_SNAKE_CASE     :							Dataset       ,						__SCREAMING_SNAKE_CASE     :							str       ,						__SCREAMING_SNAKE_CASE     :							str					)     ->		str:
      lowerCamelCase_         =						dataset
      lowerCamelCase_         =						keya
      lowerCamelCase_         =						keya






    def __len__(       self     :							str					)     ->		Union[str, Any]:
      return len(self.dataset					)






    def __getitem__(       self     :							Union[str, Any]       ,						__SCREAMING_SNAKE_CASE     :							str					)     ->		Union[str, Any]:
      return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}








"""simple docstring"""






import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image
else:





							class      lowerCamelCase__   :







												"""simple docstring"""


												@staticmethod
												def lowerCamelCase__							(       *UpperCamelCase    : List[str] ,       **UpperCamelCase    : Any  ):
																			'''simple docstring'''






																			pass





@is_pipeline_test
@require_vision
@require_torch
class      lowerCamelCase__   (     unittest.TestCase				):







					"""simple docstring"""


					__a	       =							MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING






					def lowerCamelCase__							(       self    : List[str] ,       UpperCamelCase    : Tuple ,       UpperCamelCase    : Optional[int] ,       UpperCamelCase    : Tuple  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[int]      							=					pipeline(
												    """zero-shot-object-detection""" ,       model="""hf-internal-testing/tiny-random-owlvit-object-detection"""  )

												__UpperCAmelCase   :						Tuple      							=					[
												    {
												        """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
												        """candidate_labels""": ["""cat""", """remote""", """couch"""],
												    }
												]
												return object_detector, examples






					def lowerCamelCase__							(       self    : int ,       UpperCamelCase    : Optional[int] ,       UpperCamelCase    : List[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					object_detector(examples[0] ,       threshold=0.0  )

												__UpperCAmelCase   :						Tuple      							=					len(UpperCamelCase  )
												self.assertGreater(UpperCamelCase ,       0  )
												self.assertEqual(
												    UpperCamelCase ,       [
												        {
												            """score""": ANY(UpperCamelCase  ),
												            """label""": ANY(UpperCamelCase  ),
												            """box""": {"""xmin""": ANY(UpperCamelCase  ), """ymin""": ANY(UpperCamelCase  ), """xmax""": ANY(UpperCamelCase  ), """ymax""": ANY(UpperCamelCase  )},
												        }
												        for i in range(UpperCamelCase  )
												    ] ,       )






					@require_tf
					@unittest.skip("""Zero Shot Object Detection not implemented in TF"""  )
					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												pass






					@require_torch
					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Tuple      							=					pipeline(
												    """zero-shot-object-detection""" ,       model="""hf-internal-testing/tiny-random-owlvit-object-detection"""  )

												__UpperCAmelCase   :						Tuple      							=					object_detector(
												    """./tests/fixtures/tests_samples/COCO/000000039769.png""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       threshold=0.64 ,       )

												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												        {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												        {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												        {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												        {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												        {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												        {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												        {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
												        {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												    ] ,       )

												__UpperCAmelCase   :						Any      							=					object_detector(
												    [
												        {
												            """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
												            """candidate_labels""": ["""cat""", """remote""", """couch"""],
												        }
												    ] ,       threshold=0.64 ,       )

												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        [
												            {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												            {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												            {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												            {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												            {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												            {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												            {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												            {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
												            {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												        ]
												    ] ,       )






					@require_torch
					@slow
					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Any      							=					pipeline("""zero-shot-object-detection"""  )

												__UpperCAmelCase   :						int      							=					object_detector(
												    """http://images.cocodataset.org/val2017/000000039769.jpg""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												        {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												        {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												        {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
												        {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
												    ] ,       )

												__UpperCAmelCase   :						List[str]      							=					object_detector(
												    [
												        {
												            """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
												            """candidate_labels""": ["""cat""", """remote""", """couch"""],
												        },
												        {
												            """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
												            """candidate_labels""": ["""cat""", """remote""", """couch"""],
												        },
												    ] ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        [
												            {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												            {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												            {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												            {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
												            {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
												        ],
												        [
												            {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												            {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												            {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												            {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
												            {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
												        ],
												    ] ,       )






					@require_tf
					@unittest.skip("""Zero Shot Object Detection not implemented in TF"""  )
					def lowerCamelCase__							(       self    : Any  ):
												'''simple docstring'''






												pass






					@require_torch
					@slow
					def lowerCamelCase__							(       self    : str  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[str]      							=					0.2
												__UpperCAmelCase   :						List[Any]      							=					pipeline("""zero-shot-object-detection"""  )

												__UpperCAmelCase   :						Any      							=					object_detector(
												    """http://images.cocodataset.org/val2017/000000039769.jpg""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       threshold=UpperCamelCase ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												        {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												        {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												    ] ,       )






					@require_torch
					@slow
					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					2
												__UpperCAmelCase   :						Union[str, Any]      							=					pipeline("""zero-shot-object-detection"""  )

												__UpperCAmelCase   :						List[str]      							=					object_detector(
												    """http://images.cocodataset.org/val2017/000000039769.jpg""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       top_k=UpperCamelCase ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												        {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												    ] ,       )
