





"""simple docstring"""


import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
   from PIL import Image
else:



   class   lowercase_					:

          @staticmethod
          def 		_SCREAMING_SNAKE_CASE(      *__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):






           '''simple docstring'''

           pass



@is_pipeline_test
@require_torch_or_tf
@require_vision
class   lowercase_					(  unittest.TestCase				):
       snake_case__					:				List[str]									=  MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
       snake_case__					:				List[Any]									=  TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

       def 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					ImageClassificationPipeline(model=__SCREAMING_SNAKE_CASE ,       image_processor=__SCREAMING_SNAKE_CASE ,       top_k=2  )
        snake_case__     				=					[
            Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  ),
            "http://images.cocodataset.org/val2017/000000039769.jpg",
        ]
        return image_classifier, examples

       def 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					image_classifier("./tests/fixtures/tests_samples/COCO/000000039769.png"  )

        self.assertEqual(
            __SCREAMING_SNAKE_CASE ,       [
                {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
            ] ,       )

        import datasets

        snake_case__     				=					datasets.load_dataset("hf-internal-testing/fixtures_image_utils" ,       "image" ,       split="test"  )

        # Accepts URL + PIL.Image + lists
        snake_case__     				=					image_classifier(
            [
                Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  ),
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                # RGBA
                dataset[0]["file"],
                # LA
                dataset[1]["file"],
                # L
                dataset[2]["file"],
            ]  )
        self.assertEqual(
            __SCREAMING_SNAKE_CASE ,       [
                [
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                ],
                [
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                ],
                [
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                ],
                [
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                ],
                [
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                    {"score": ANY(__SCREAMING_SNAKE_CASE  ), "label": ANY(__SCREAMING_SNAKE_CASE  )},
                ],
            ] ,       )

       @require_torch
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					"hf-internal-testing/tiny-random-vit"
        snake_case__     				=					pipeline("image-classification" ,       model=__SCREAMING_SNAKE_CASE  )

        snake_case__     				=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"  )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}] ,       )

        snake_case__     				=					image_classifier(
            [
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                "http://images.cocodataset.org/val2017/000000039769.jpg",
            ] ,       top_k=2 ,       )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [
                [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}],
                [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}],
            ] ,       )

       @require_tf
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					"hf-internal-testing/tiny-random-vit"
        snake_case__     				=					pipeline("image-classification" ,       model=__SCREAMING_SNAKE_CASE ,       framework="tf"  )

        snake_case__     				=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"  )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}] ,       )

        snake_case__     				=					image_classifier(
            [
                "http://images.cocodataset.org/val2017/000000039769.jpg",
                "http://images.cocodataset.org/val2017/000000039769.jpg",
            ] ,       top_k=2 ,       )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [
                [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}],
                [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}],
            ] ,       )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					PreTrainedTokenizer()

        # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
        snake_case__     				=					pipeline(
            "image-classification" ,       model="hf-internal-testing/tiny-random-vit" ,       tokenizer=__SCREAMING_SNAKE_CASE  )

        self.assertIs(image_classifier.tokenizer ,       __SCREAMING_SNAKE_CASE  )

       @slow
       @require_torch
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					pipeline("image-classification" ,       model="deepmind/vision-perceiver-conv"  )
        snake_case__     				=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"  )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [
                {"score": 0.4385, "label": "tabby, tabby cat"},
                {"score": 0.321, "label": "tiger cat"},
                {"score": 0.0502, "label": "Egyptian cat"},
                {"score": 0.0137, "label": "crib, cot"},
                {"score": 0.007, "label": "radiator"},
            ] ,       )

        snake_case__     				=					pipeline("image-classification" ,       model="deepmind/vision-perceiver-fourier"  )
        snake_case__     				=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"  )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [
                {"score": 0.5658, "label": "tabby, tabby cat"},
                {"score": 0.1309, "label": "tiger cat"},
                {"score": 0.0722, "label": "Egyptian cat"},
                {"score": 0.0707, "label": "remote control, remote"},
                {"score": 0.0082, "label": "computer keyboard, keypad"},
            ] ,       )

        snake_case__     				=					pipeline("image-classification" ,       model="deepmind/vision-perceiver-learned"  )
        snake_case__     				=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"  )
        self.assertEqual(
            nested_simplify(__SCREAMING_SNAKE_CASE ,       decimals=4  ) ,       [
                {"score": 0.3022, "label": "tabby, tabby cat"},
                {"score": 0.2362, "label": "Egyptian cat"},
                {"score": 0.1856, "label": "tiger cat"},
                {"score": 0.0324, "label": "remote control, remote"},
                {"score": 0.0096, "label": "quilt, comforter, comfort, puff"},
            ] ,       )








"""simple docstring"""


import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
       SpeechaTextaDecoder,
       SpeechaTextaForCausalLM,
   )



@require_torch
class   lowercase_					:

       def __init__(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE=99 ,       __SCREAMING_SNAKE_CASE=13 ,       __SCREAMING_SNAKE_CASE=16 ,       __SCREAMING_SNAKE_CASE=7 ,       __SCREAMING_SNAKE_CASE=True ,       __SCREAMING_SNAKE_CASE=True ,       __SCREAMING_SNAKE_CASE=True ,       __SCREAMING_SNAKE_CASE=False ,       __SCREAMING_SNAKE_CASE=True ,       __SCREAMING_SNAKE_CASE=2 ,       __SCREAMING_SNAKE_CASE=32 ,       __SCREAMING_SNAKE_CASE=4 ,       __SCREAMING_SNAKE_CASE=4 ,       __SCREAMING_SNAKE_CASE=30 ,       __SCREAMING_SNAKE_CASE=0 ,       __SCREAMING_SNAKE_CASE=1 ,       __SCREAMING_SNAKE_CASE=2 ,       __SCREAMING_SNAKE_CASE=None ,       ):






        '''simple docstring'''

        snake_case__     				=					parent
        snake_case__     				=					batch_size
        snake_case__     				=					decoder_seq_length
        # For common tests
        snake_case__     				=					self.decoder_seq_length
        snake_case__     				=					is_training
        snake_case__     				=					use_attention_mask
        snake_case__     				=					use_labels

        snake_case__     				=					vocab_size
        snake_case__     				=					d_model
        snake_case__     				=					d_model
        snake_case__     				=					decoder_layers
        snake_case__     				=					decoder_layers
        snake_case__     				=					decoder_ffn_dim
        snake_case__     				=					decoder_attention_heads
        snake_case__     				=					decoder_attention_heads
        snake_case__     				=					eos_token_id
        snake_case__     				=					bos_token_id
        snake_case__     				=					pad_token_id
        snake_case__     				=					decoder_start_token_id
        snake_case__     				=					use_cache
        snake_case__     				=					max_position_embeddings

        snake_case__     				=					None
        snake_case__     				=					decoder_seq_length
        snake_case__     				=					2
        snake_case__     				=					1

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					ids_tensor([self.batch_size, self.decoder_seq_length] ,       self.vocab_size  )

        snake_case__     				=					None
        if self.use_attention_mask:
         snake_case__     				=					ids_tensor([self.batch_size, self.decoder_seq_length] ,       vocab_size=2  )

        snake_case__     				=					None
        if self.use_labels:
         snake_case__     				=					ids_tensor([self.batch_size, self.decoder_seq_length] ,       self.vocab_size  )

        snake_case__     				=					SpeechaTextaConfig(
            vocab_size=self.vocab_size ,       d_model=self.d_model ,       decoder_layers=self.decoder_layers ,       decoder_ffn_dim=self.decoder_ffn_dim ,       decoder_attention_heads=self.decoder_attention_heads ,       eos_token_id=self.eos_token_id ,       bos_token_id=self.bos_token_id ,       use_cache=self.use_cache ,       pad_token_id=self.pad_token_id ,       decoder_start_token_id=self.decoder_start_token_id ,       max_position_embeddings=self.max_position_embeddings ,       )

        return (
            config,
            input_ids,
            attention_mask,
            lm_labels,
        )

       def 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       ):






        '''simple docstring'''

        snake_case__     				=					True
        snake_case__     				=					SpeechaTextaDecoder(config=__SCREAMING_SNAKE_CASE  ).to(__SCREAMING_SNAKE_CASE  ).eval()
        snake_case__     				=					input_ids[:2]

        input_ids[input_ids == 0] += 1
        # first forward pass
        snake_case__     				=					model(__SCREAMING_SNAKE_CASE ,       use_cache=__SCREAMING_SNAKE_CASE  )
        snake_case__     				=					model(__SCREAMING_SNAKE_CASE  )
        snake_case__     				=					model(__SCREAMING_SNAKE_CASE ,       use_cache=__SCREAMING_SNAKE_CASE  )

        self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE  ) == len(__SCREAMING_SNAKE_CASE  )  )
        self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE  ) == len(__SCREAMING_SNAKE_CASE  ) + 1  )

        snake_case__     				=					outputs["past_key_values"]

        # create hypothetical next token and extent to next_input_ids
        snake_case__     				=					ids_tensor((2, 1) ,       config.vocab_size - 1  ) + 1

        # append to next input_ids and
        snake_case__     				=					torch.cat([input_ids, next_tokens] ,       dim=-1  )

        print(__SCREAMING_SNAKE_CASE  )

        snake_case__     				=					model(__SCREAMING_SNAKE_CASE  )["last_hidden_state"]
        snake_case__     				=					model(__SCREAMING_SNAKE_CASE ,       past_key_values=__SCREAMING_SNAKE_CASE  )["last_hidden_state"]

        # select random slice
        snake_case__     				=					ids_tensor((1,) ,       output_from_past.shape[-1]  ).item()
        snake_case__     				=					output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
        snake_case__     				=					output_from_past[:, 0, random_slice_idx].detach()

        # test that outputs are equal for slice
        assert torch.allclose(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       atol=1e-3  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					self.prepare_config_and_inputs()
        (
            (
            snake_case__
        )				, (
            snake_case__
        )				, (
            snake_case__
        )				, (
            snake_case__
        )				, 
        )     				=					config_and_inputs

        snake_case__     				=					{
            "input_ids": input_ids,
            "attention_mask": attention_mask,
        }
        return config, inputs_dict



@require_torch
class   lowercase_					(  __lowerCAmelCase					,__lowerCAmelCase					,__lowerCAmelCase					,unittest.TestCase				):
       snake_case__					:				Tuple									=  (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
       snake_case__					:				Optional[Any]									=  (SpeechaTextaForCausalLM,) if is_torch_available() else ()
       snake_case__					:				List[Any]									=  {"""text-generation""": SpeechaTextaForCausalLM} if is_torch_available() else {}
       snake_case__					:				Dict									=  True
       snake_case__					:				Dict									=  False

       def 		_SCREAMING_SNAKE_CASE(      self ,       ):






        '''simple docstring'''

        snake_case__     				=					SpeechaTextaStandaloneDecoderModelTester(self ,       is_training=__SCREAMING_SNAKE_CASE  )
        snake_case__     				=					ConfigTester(self ,       config_class=__SCREAMING_SNAKE_CASE  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        pass

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        pass

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        pass

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        self.config_tester.run_common_tests()

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_decoder_model_past(*__SCREAMING_SNAKE_CASE  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        return

