from collections import OrderedDict
from typing import Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...feature_extraction_utils import FeatureExtractionMixin
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType, logging


__lowercase											=      logging.get_logger(__name__)

__lowercase											=      {
    '''deepmind/language-perceiver''': '''https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json''',
    # See all Perceiver models at https://huggingface.co/models?filter=perceiver
}


class 			lowerCamelCase_  (     UpperCAmelCase_				):






    '''simple docstring'''






    a__			:		int      			=   """perceiver"""







    def __init__(			self				,				__lowercase=256				,				__lowercase=1_280				,				__lowercase=768				,				__lowercase=1				,				__lowercase=26				,				__lowercase=8				,				__lowercase=8				,				__lowercase=None				,				__lowercase=None				,				__lowercase="kv"				,				__lowercase=1				,				__lowercase=1				,				__lowercase="gelu"				,				__lowercase=0.1				,				__lowercase=0.02				,				__lowercase=1E-1_2				,				__lowercase=True				,				__lowercase=262				,				__lowercase=2_048				,				__lowercase=56				,				__lowercase=[368, 496]				,				__lowercase=16				,				__lowercase=1_920				,				__lowercase=16				,				__lowercase=[1, 16, 224, 224]				,				**__lowercase				,				) ->			Dict:
        super().__init__(**__lowercase)

        __UpperCamelCase  :Optional[Any]    						=	num_latents
        __UpperCamelCase  :List[Any]    						=	d_latents
        __UpperCamelCase  :List[str]    						=	d_model
        __UpperCamelCase  :Tuple    						=	num_blocks
        __UpperCamelCase  :List[Any]    						=	num_self_attends_per_block
        __UpperCamelCase  :Any    						=	num_self_attention_heads
        __UpperCamelCase  :List[str]    						=	num_cross_attention_heads
        __UpperCamelCase  :Tuple    						=	qk_channels
        __UpperCamelCase  :int    						=	v_channels
        __UpperCamelCase  :List[str]    						=	cross_attention_shape_for_attention
        __UpperCamelCase  :str    						=	self_attention_widening_factor
        __UpperCamelCase  :Optional[int]    						=	cross_attention_widening_factor
        __UpperCamelCase  :List[str]    						=	hidden_act
        __UpperCamelCase  :Optional[int]    						=	attention_probs_dropout_prob
        __UpperCamelCase  :Optional[int]    						=	initializer_range
        __UpperCamelCase  :Any    						=	layer_norm_eps
        __UpperCamelCase  :Any    						=	use_query_residual
        # masked language modeling attributes
        __UpperCamelCase  :List[str]    						=	vocab_size
        __UpperCamelCase  :Any    						=	max_position_embeddings
        # image classification attributes
        __UpperCamelCase  :List[str]    						=	image_size
        # flow attributes
        __UpperCamelCase  :Optional[Any]    						=	train_size
        # multimodal autoencoding attributes
        __UpperCamelCase  :str    						=	num_frames
        __UpperCamelCase  :List[str]    						=	audio_samples_per_frame
        __UpperCamelCase  :int    						=	samples_per_patch
        __UpperCamelCase  :Optional[Any]    						=	output_shape


class 			lowerCamelCase_  (     UpperCAmelCase_				):






    '''simple docstring'''






    @property
    def     UpperCamelCase__     (			self) ->			Mapping[str, Mapping[int, str]]:
        if self.task == "multiple-choice":
            __UpperCamelCase  :List[str]    						=	{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
        else:
            __UpperCamelCase  :Union[str, Any]    						=	{0: '''batch''', 1: '''sequence'''}
        return OrderedDict(
            [
                ('''inputs''', dynamic_axis),
                ('''attention_mask''', dynamic_axis),
            ])







    @property
    def     UpperCamelCase__     (			self) ->			float:
        return 1E-4







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase = -1				,				__lowercase = -1				,				__lowercase = -1				,				__lowercase = False				,				__lowercase = None				,				__lowercase = 3				,				__lowercase = 40				,				__lowercase = 40				,				) ->			Mapping[str, Any]:
        # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified

        if isinstance(__lowercase				,				__lowercase):
            # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
            __UpperCamelCase  :Any    						=	compute_effective_axis_dimension(
                __lowercase				,				fixed_dimension=OnnxConfig.default_fixed_batch				,				num_token_to_add=0)
            # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
            __UpperCamelCase  :Union[str, Any]    						=	preprocessor.num_special_tokens_to_add(__lowercase)
            __UpperCamelCase  :Union[str, Any]    						=	compute_effective_axis_dimension(
                __lowercase				,				fixed_dimension=OnnxConfig.default_fixed_sequence				,				num_token_to_add=__lowercase)
            # Generate dummy inputs according to compute batch and sequence
            __UpperCamelCase  :Tuple    						=	[''' '''.join(['''a''']) * seq_length] * batch_size
            __UpperCamelCase  :List[Any]    						=	dict(preprocessor(__lowercase				,				return_tensors=__lowercase))
            __UpperCamelCase  :Dict    						=	inputs.pop('''input_ids''')
            return inputs
        elif isinstance(__lowercase				,				__lowercase) and preprocessor.model_input_names[0] == "pixel_values":
            # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
            __UpperCamelCase  :Dict    						=	compute_effective_axis_dimension(__lowercase				,				fixed_dimension=OnnxConfig.default_fixed_batch)
            __UpperCamelCase  :Union[str, Any]    						=	self._generate_dummy_images(__lowercase				,				__lowercase				,				__lowercase				,				__lowercase)
            __UpperCamelCase  :Tuple    						=	dict(preprocessor(images=__lowercase				,				return_tensors=__lowercase))
            __UpperCamelCase  :List[Any]    						=	inputs.pop('''pixel_values''')
            return inputs
        else:
            raise ValueError(
                '''Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.''')






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     UpperCamelCase__     (			*__lowercase				,				**__lowercase) ->			Dict:
            pass


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






    '''simple docstring'''






    a__			:		str      			=   MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase				,				__lowercase) ->			str:
        __UpperCamelCase  :Union[str, Any]    						=	pipeline(
            '''zero-shot-object-detection'''				,				model='''hf-internal-testing/tiny-random-owlvit-object-detection''')

        __UpperCamelCase  :Dict    						=	[
            {
                '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
                '''candidate_labels''': ['''cat''', '''remote''', '''couch'''],
            }
        ]
        return object_detector, examples







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase) ->			Optional[Any]:
        __UpperCamelCase  :Optional[Any]    						=	object_detector(examples[0]				,				threshold=0.0)

        __UpperCamelCase  :Dict    						=	len(__lowercase)
        self.assertGreater(__lowercase				,				0)
        self.assertEqual(
            __lowercase				,				[
                {
                    '''score''': ANY(__lowercase),
                    '''label''': ANY(__lowercase),
                    '''box''': {'''xmin''': ANY(__lowercase), '''ymin''': ANY(__lowercase), '''xmax''': ANY(__lowercase), '''ymax''': ANY(__lowercase)},
                }
                for i in range(__lowercase)
            ]				,				)







    @require_tf
    @unittest.skip('''Zero Shot Object Detection not implemented in TF''')
    def     UpperCamelCase__     (			self) ->			int:
        pass







    @require_torch
    def     UpperCamelCase__     (			self) ->			Any:
        __UpperCamelCase  :Tuple    						=	pipeline(
            '''zero-shot-object-detection'''				,				model='''hf-internal-testing/tiny-random-owlvit-object-detection''')

        __UpperCamelCase  :str    						=	object_detector(
            '''./tests/fixtures/tests_samples/COCO/000000039769.png'''				,				candidate_labels=['''cat''', '''remote''', '''couch''']				,				threshold=0.64				,				)

        self.assertEqual(
            nested_simplify(__lowercase				,				decimals=4)				,				[
                {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 274, '''xmax''': 93, '''ymax''': 297}},
                {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
            ]				,				)

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

        self.assertEqual(
            nested_simplify(__lowercase				,				decimals=4)				,				[
                [
                    {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                    {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                    {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                    {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                    {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                    {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                    {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                    {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 274, '''xmax''': 93, '''ymax''': 297}},
                    {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                ]
            ]				,				)







    @require_torch
    @slow
    def     UpperCamelCase__     (			self) ->			Optional[int]:
        __UpperCamelCase  :List[str]    						=	pipeline('''zero-shot-object-detection''')

        __UpperCamelCase  :List[str]    						=	object_detector(
            '''http://images.cocodataset.org/val2017/000000039769.jpg'''				,				candidate_labels=['''cat''', '''remote''', '''couch''']				,				)
        self.assertEqual(
            nested_simplify(__lowercase				,				decimals=4)				,				[
                {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
            ]				,				)

        __UpperCamelCase  :Dict    						=	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(__lowercase				,				decimals=4)				,				[
                [
                    {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                    {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                    {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                    {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                    {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                ],
                [
                    {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                    {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                    {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                    {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                    {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                ],
            ]				,				)







    @require_tf
    @unittest.skip('''Zero Shot Object Detection not implemented in TF''')
    def     UpperCamelCase__     (			self) ->			Dict:
        pass







    @require_torch
    @slow
    def     UpperCamelCase__     (			self) ->			str:
        __UpperCamelCase  :Tuple    						=	0.2
        __UpperCamelCase  :str    						=	pipeline('''zero-shot-object-detection''')

        __UpperCamelCase  :Any    						=	object_detector(
            '''http://images.cocodataset.org/val2017/000000039769.jpg'''				,				candidate_labels=['''cat''', '''remote''', '''couch''']				,				threshold=__lowercase				,				)
        self.assertEqual(
            nested_simplify(__lowercase				,				decimals=4)				,				[
                {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
            ]				,				)







    @require_torch
    @slow
    def     UpperCamelCase__     (			self) ->			Any:
        __UpperCamelCase  :Optional[int]    						=	2
        __UpperCamelCase  :Union[str, Any]    						=	pipeline('''zero-shot-object-detection''')

        __UpperCamelCase  :Any    						=	object_detector(
            '''http://images.cocodataset.org/val2017/000000039769.jpg'''				,				candidate_labels=['''cat''', '''remote''', '''couch''']				,				top_k=__lowercase				,				)
        self.assertEqual(
            nested_simplify(__lowercase				,				decimals=4)				,				[
                {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
            ]				,				)





