






import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

snake_case__      :	Dict       	=      logging.get_logger(__name__)


class 						_a       (  enum.Enum    ):






  """simple docstring"""





  A_						=   0
  A_						=   1




@add_end_docstrings(UpperCAmelCase__    )
class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """generated"""




  def __init__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Union[str, Any]:
     super().__init__(*_UpperCAmelCase		,		**_UpperCAmelCase )

     self.check_model_type(
         TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
         if self.framework == 'tf'
         else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)			-> Dict:
     UpperCamelCase_									=     {}
     if truncation is not None:
        UpperCamelCase_									=     truncation

     UpperCamelCase_									=     generate_kwargs

     UpperCamelCase_									=     {}
     if return_tensors is not None and return_type is None:
        UpperCamelCase_									=     ReturnType.TENSORS if return_tensors else ReturnType.TEXT
     if return_type is not None:
        UpperCamelCase_									=     return_type

     if clean_up_tokenization_spaces is not None:
        UpperCamelCase_									=     clean_up_tokenization_spaces

     if stop_sequence is not None:
        UpperCamelCase_									=     self.tokenizer.encode(_UpperCAmelCase		,		add_special_tokens=_UpperCAmelCase )
        if len(_UpperCAmelCase ) > 1:
           warnings.warn(
               'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
               ' the stop sequence will be used as the stop sequence string in the interim.' )
        UpperCamelCase_									=     stop_sequence_ids[0]

     return preprocess_params, forward_params, postprocess_params




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Dict:
     return True




  def    _UpperCAmelCase     (     self		,		*_UpperCAmelCase		,		_UpperCAmelCase )			-> Dict:
     UpperCamelCase_									=     self.model.config.prefix if self.model.config.prefix is not None else ''
     if isinstance(args[0]		,		_UpperCAmelCase ):
        if self.tokenizer.pad_token_id is None:
           raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input' )
        UpperCamelCase_									=     ([prefix + arg for arg in args[0]],)
        UpperCamelCase_									=     True

     elif isinstance(args[0]		,		_UpperCAmelCase ):
        UpperCamelCase_									=     (prefix + args[0],)
        UpperCamelCase_									=     False
     else:
        raise ValueError(
            f""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" )
     UpperCamelCase_									=     self.tokenizer(*_UpperCAmelCase		,		padding=_UpperCAmelCase		,		truncation=_UpperCAmelCase		,		return_tensors=self.framework )
     # This is produced by tokenizers but is an invalid generate kwargs
     if "token_type_ids" in inputs:
        del inputs["token_type_ids"]
     return inputs




  def __call__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Optional[Any]:
     UpperCamelCase_									=     super().__call__(*_UpperCAmelCase		,		**_UpperCAmelCase )
     if (
         isinstance(args[0]		,		_UpperCAmelCase )
         and all(isinstance(_UpperCAmelCase		,		_UpperCAmelCase ) for el in args[0] )
         and all(len(_UpperCAmelCase ) == 1 for res in result )
     ):
        return [res[0] for res in result]
     return result




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=TruncationStrategy.DO_NOT_TRUNCATE		,		**_UpperCAmelCase )			-> Union[str, Any]:
     UpperCamelCase_									=     self._parse_and_tokenize(_UpperCAmelCase		,		truncation=_UpperCAmelCase		,		**_UpperCAmelCase )
     return inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> Union[str, Any]:
     if self.framework == "pt":
        UpperCamelCase_		,      UpperCamelCase_									=     model_inputs['input_ids'].shape
     elif self.framework == "tf":
        UpperCamelCase_		,      UpperCamelCase_									=     tf.shape(model_inputs['input_ids'] ).numpy()

     UpperCamelCase_									=     generate_kwargs.get('min_length'		,		self.model.config.min_length )
     UpperCamelCase_									=     generate_kwargs.get('max_length'		,		self.model.config.max_length )
     self.check_inputs(_UpperCAmelCase		,		generate_kwargs['min_length']		,		generate_kwargs['max_length'] )
     UpperCamelCase_									=     self.model.generate(**_UpperCAmelCase		,		**_UpperCAmelCase )
     UpperCamelCase_									=     output_ids.shape[0]
     if self.framework == "pt":
        UpperCamelCase_									=     output_ids.reshape(_UpperCAmelCase		,		out_b // in_b		,		*output_ids.shape[1:] )
     elif self.framework == "tf":
        UpperCamelCase_									=     tf.reshape(_UpperCAmelCase		,		(in_b, out_b // in_b, *output_ids.shape[1:]) )
     return {"output_ids": output_ids}




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=ReturnType.TEXT		,		_UpperCAmelCase=False )			-> Optional[int]:
     UpperCamelCase_									=     []
     for output_ids in model_outputs["output_ids"][0]:
        if return_type == ReturnType.TENSORS:
           UpperCamelCase_									=     {f"""{self.return_name}_token_ids""": output_ids}
        elif return_type == ReturnType.TEXT:
           UpperCamelCase_									=     {
               f"""{self.return_name}_text""": self.tokenizer.decode(
                   _UpperCAmelCase		,		skip_special_tokens=_UpperCAmelCase		,		clean_up_tokenization_spaces=_UpperCAmelCase		,		)
           }
        records.append(_UpperCAmelCase )
     return records




@add_end_docstrings(UpperCAmelCase__    )
class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """summary"""




  def __call__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Tuple:
     return super().__call__(*_UpperCAmelCase		,		**_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> bool:
     if max_length < min_length:
        logger.warning(f"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" )

     if input_length < max_length:
        logger.warning(
            f"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """
            'a summarization task, where outputs shorter than the input are typically wanted, you might '
            f"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" )




@add_end_docstrings(UpperCAmelCase__    )
class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """translation"""




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     if input_length > 0.9 * max_length:
        logger.warning(
            f"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """
            'increasing your max_length manually, e.g. translator(\'...\', max_length=400)' )
     return True




  def    _UpperCAmelCase     (     self		,		*_UpperCAmelCase		,		_UpperCAmelCase=TruncationStrategy.DO_NOT_TRUNCATE		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None )			-> Union[str, Any]:
     if getattr(self.tokenizer		,		'_build_translation_inputs'		,		_UpperCAmelCase ):
        return self.tokenizer._build_translation_inputs(
            *_UpperCAmelCase		,		return_tensors=self.framework		,		truncation=_UpperCAmelCase		,		src_lang=_UpperCAmelCase		,		tgt_lang=_UpperCAmelCase )
     else:
        return super()._parse_and_tokenize(*_UpperCAmelCase		,		truncation=_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		**_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     super()._sanitize_parameters(**_UpperCAmelCase )
     if src_lang is not None:
        UpperCamelCase_									=     src_lang
     if tgt_lang is not None:
        UpperCamelCase_									=     tgt_lang
     if src_lang is None and tgt_lang is None:
        # Backward compatibility, direct arguments use is preferred.
        UpperCamelCase_									=     kwargs.get('task'		,		self.task )
        UpperCamelCase_									=     task.split('_' )
        if task and len(_UpperCAmelCase ) == 4:
           # translation, XX, to YY
           UpperCamelCase_									=     items[1]
           UpperCamelCase_									=     items[3]
     return preprocess_params, forward_params, postprocess_params




  def __call__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Any:
     return super().__call__(*_UpperCAmelCase		,		**_UpperCAmelCase )













import inspect
import unittest

from transformers import ViTMSNConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import ViTMSNForImageClassification, ViTMSNModel
 from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor


class 						_a       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=30		,		_UpperCAmelCase=2		,		_UpperCAmelCase=3		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=32		,		_UpperCAmelCase=5		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=10		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=None		,		)			-> Optional[Any]:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     image_size
     UpperCamelCase_									=     patch_size
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     use_labels
     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     hidden_dropout_prob
     UpperCamelCase_									=     attention_probs_dropout_prob
     UpperCamelCase_									=     type_sequence_label_size
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     scope

     # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
     UpperCamelCase_									=     (image_size // patch_size) ** 2
     UpperCamelCase_									=     num_patches + 1




  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     UpperCamelCase_									=     None
     if self.use_labels:
        UpperCamelCase_									=     ids_tensor([self.batch_size]		,		self.type_sequence_label_size )

     UpperCamelCase_									=     self.get_config()

     return config, pixel_values, labels




  def    _UpperCAmelCase     (     self )			-> int:
     return ViTMSNConfig(
         image_size=self.image_size		,		patch_size=self.patch_size		,		num_channels=self.num_channels		,		hidden_size=self.hidden_size		,		num_hidden_layers=self.num_hidden_layers		,		num_attention_heads=self.num_attention_heads		,		intermediate_size=self.intermediate_size		,		hidden_act=self.hidden_act		,		hidden_dropout_prob=self.hidden_dropout_prob		,		attention_probs_dropout_prob=self.attention_probs_dropout_prob		,		initializer_range=self.initializer_range		,		)




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Any:
     UpperCamelCase_									=     ViTMSNModel(config=_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> str:
     UpperCamelCase_									=     self.type_sequence_label_size
     UpperCamelCase_									=     ViTMSNForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase		,		labels=_UpperCAmelCase )
     print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}' )
     print('Labels: {labels}' )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )

     # test greyscale images
     UpperCamelCase_									=     1
     UpperCamelCase_									=     ViTMSNForImageClassification(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()

     UpperCamelCase_									=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size) )




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     config_and_inputs
     UpperCamelCase_									=     {'pixel_values': pixel_values}
     return config, inputs_dict




@require_torch
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  A_						=   (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
  A_						=   (
      {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification}
      if is_torch_available()
      else {}
  )

  A_						=   False
  A_						=   False
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     ViTMSNModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase		,		has_text_modality=_UpperCAmelCase		,		hidden_size=37 )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     self.config_tester.run_common_tests()




  @unittest.skip(reason='ViTMSN does not use inputs_embeds' )
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     pass




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module) )
        UpperCamelCase_									=     model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(_UpperCAmelCase		,		nn.Linear ) )




  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        UpperCamelCase_									=     inspect.signature(model.forward )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        UpperCamelCase_									=     [*signature.parameters.keys()]

        UpperCamelCase_									=     ['pixel_values']
        self.assertListEqual(arg_names[:1]		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> Dict:
     for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase_									=     ViTMSNModel.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )






def     _snake_case    ():
   UpperCamelCase_									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
   return image


@require_torch
@require_vision
class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  @cached_property
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     return ViTImageProcessor.from_pretrained('facebook/vit-msn-small' ) if is_vision_available() else None




  @slow
  def    _UpperCAmelCase     (     self )			-> List[str]:
     torch.manual_seed(2 )
     UpperCamelCase_									=     ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small' ).to(_UpperCAmelCase )

     UpperCamelCase_									=     self.default_image_processor
     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' ).to(_UpperCAmelCase )

     # forward pass
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )

     # verify the logits
     UpperCamelCase_									=     torch.Size((1, 1000) )
     self.assertEqual(outputs.logits.shape		,		_UpperCAmelCase )

     UpperCamelCase_									=     torch.tensor([-0.0_8_0_3, -0.4_4_5_4, -0.2_3_7_5] ).to(_UpperCAmelCase )

     self.assertTrue(torch.allclose(outputs.logits[0, :3]		,		_UpperCAmelCase		,		atol=1e-4 ) )





