



from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


_lowercase     							=						logging.get_logger(__name__)
class 				__A					( A_      ):





			def        _snake_case    (self							,    __magic_name__				):
						if isinstance(__magic_name__							,    __magic_name__				):
									lowerCamelCase__ :      Any								=		[label.strip() for label in labels.split(""","""				) if label.strip()]
						return labels





			def __call__(self							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						if len(__magic_name__				) == 0 or len(__magic_name__				) == 0:
									raise ValueError("""You must include at least one label and at least one sequence."""				)
						if hypothesis_template.format(labels[0]				) == hypothesis_template:
									raise ValueError(
									    (
									        """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
									        """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
									    ).format(__magic_name__				)				)

						if isinstance(__magic_name__							,    __magic_name__				):
									lowerCamelCase__ :      str								=		[sequences]

						lowerCamelCase__ :      Optional[int]								=		[]
						for sequence in sequences:
									sequence_pairs.extend([[sequence, hypothesis_template.format(__magic_name__				)] for label in labels]				)

						return sequence_pairs, sequences







@add_end_docstrings(A_      )
class 				__A					( A_      ):





			def __init__(self							,    __magic_name__=ZeroShotClassificationArgumentHandler()							,    *__magic_name__							,    **__magic_name__				):
						lowerCamelCase__ :      Union[str, Any]								=		args_parser
						super().__init__(*__magic_name__							,    **__magic_name__				)
						if self.entailment_id == -1:
									logger.warning(
									    """Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to """
									    """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."""				)





			@property
			def        _snake_case    (self				):
						for label, ind in self.model.config.labelaid.items():
									if label.lower().startswith("""entail"""				):
												return ind
						return -1





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=TruncationStrategy.ONLY_FIRST							,    **__magic_name__				):
						lowerCamelCase__ :      Dict								=		self.framework
						if self.tokenizer.pad_token is None:
									# Override for tokenizers not supporting padding
									logger.error(
									    """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
									    """ `pad_token=eos_token`"""				)
									lowerCamelCase__ :      str								=		self.tokenizer.eos_token
						try:
									lowerCamelCase__ :      List[Any]								=		self.tokenizer(
									    __magic_name__							,    add_special_tokens=__magic_name__							,    return_tensors=__magic_name__							,    padding=__magic_name__							,    truncation=__magic_name__							,    )
						except Exception as e:
									if "too short" in str(__magic_name__				):
												# tokenizers might yell that we want to truncate
												# to a value that is not even reached by the input.
												# In that case we don't want to truncate.
												# It seems there's not a really better way to catch that
												# exception.

												lowerCamelCase__ :      Dict								=		self.tokenizer(
												    __magic_name__							,    add_special_tokens=__magic_name__							,    return_tensors=__magic_name__							,    padding=__magic_name__							,    truncation=TruncationStrategy.DO_NOT_TRUNCATE							,    )
									else:
												raise e

						return inputs





			def        _snake_case    (self							,    **__magic_name__				):
						if kwargs.get("""multi_class"""							,    __magic_name__				) is not None:
									lowerCamelCase__ :      int								=		kwargs["""multi_class"""]
									logger.warning(
									    """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
									    """`multi_class` will be removed in a future version of Transformers."""				)
						lowerCamelCase__ :      int								=		{}
						if "candidate_labels" in kwargs:
									lowerCamelCase__ :      List[Any]								=		self._args_parser._parse_labels(kwargs["""candidate_labels"""]				)
						if "hypothesis_template" in kwargs:
									lowerCamelCase__ :      Any								=		kwargs["""hypothesis_template"""]

						lowerCamelCase__ :      List[Any]								=		{}
						if "multi_label" in kwargs:
									lowerCamelCase__ :      Any								=		kwargs["""multi_label"""]
						return preprocess_params, {}, postprocess_params





			def __call__(self							,    __magic_name__							,    *__magic_name__							,    **__magic_name__							,    ):
						if len(__magic_name__				) == 0:
									pass
						elif len(__magic_name__				) == 1 and "candidate_labels" not in kwargs:
									lowerCamelCase__ :      Union[str, Any]								=		args[0]
						else:
									raise ValueError(f"Unable to understand extra arguments {args}"				)

						return super().__call__(__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__=None							,    __magic_name__="This example is {}."				):
						lowerCamelCase__ :      Optional[Any]								=		self._args_parser(__magic_name__							,    __magic_name__							,    __magic_name__				)

						for i, (candidate_label, sequence_pair) in enumerate(zip(__magic_name__							,    __magic_name__				)				):
									lowerCamelCase__ :      Union[str, Any]								=		self._parse_and_tokenize([sequence_pair]				)

									yield {
									    "candidate_label": candidate_label,
									    "sequence": sequences[0],
									    "is_last": i == len(__magic_name__				) - 1,
									    **model_input,
									}





			def        _snake_case    (self							,    __magic_name__				):
						lowerCamelCase__ :      int								=		inputs["""candidate_label"""]
						lowerCamelCase__ :      int								=		inputs["""sequence"""]
						lowerCamelCase__ :      str								=		{k: inputs[k] for k in self.tokenizer.model_input_names}
						lowerCamelCase__ :      Optional[int]								=		self.model(**__magic_name__				)

						lowerCamelCase__ :      str								=		{
						    """candidate_label""": candidate_label,
						    """sequence""": sequence,
						    """is_last""": inputs["""is_last"""],
						    **outputs,
						}
						return model_outputs





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__=False				):
						lowerCamelCase__ :      Union[str, Any]								=		[outputs["""candidate_label"""] for outputs in model_outputs]
						lowerCamelCase__ :      Optional[int]								=		[outputs["""sequence"""] for outputs in model_outputs]
						lowerCamelCase__ :      Any								=		np.concatenate([output["""logits"""].numpy() for output in model_outputs]				)
						lowerCamelCase__ :      List[Any]								=		logits.shape[0]
						lowerCamelCase__ :      Union[str, Any]								=		len(__magic_name__				)
						lowerCamelCase__ :      int								=		N // n
						lowerCamelCase__ :      int								=		logits.reshape((num_sequences, n, -1)				)

						if multi_label or len(__magic_name__				) == 1:
									# softmax over the entailment vs. contradiction dim for each label independently
									lowerCamelCase__ :      int								=		self.entailment_id
									lowerCamelCase__ :      str								=		-1 if entailment_id == 0 else 0
									lowerCamelCase__ :      int								=		reshaped_outputs[..., [contradiction_id, entailment_id]]
									lowerCamelCase__ :      Optional[int]								=		np.exp(__magic_name__				) / np.exp(__magic_name__				).sum(-1							,    keepdims=__magic_name__				)
									lowerCamelCase__ :      Tuple								=		scores[..., 1]
						else:
									# softmax the "entailment" logits over all candidate labels
									lowerCamelCase__ :      Dict								=		reshaped_outputs[..., self.entailment_id]
									lowerCamelCase__ :      str								=		np.exp(__magic_name__				) / np.exp(__magic_name__				).sum(-1							,    keepdims=__magic_name__				)

						lowerCamelCase__ :      int								=		list(reversed(scores[0].argsort()				)				)
						return {
						    "sequence": sequences[0],
						    "labels": [candidate_labels[i] for i in top_inds],
						    "scores": scores[0, top_inds].tolist(),
						}








import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
				from transformers.models.mobilevitva.modeling_mobilevitva import (
				    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
				    make_divisible,
				)


if is_vision_available():
				from PIL import Image

				from transformers import MobileViTImageProcessor
class 				__A					( A_      ):





			def        _snake_case    (self				):
						lowerCamelCase__ :      Dict								=		self.config_class(**self.inputs_dict				)
						self.parent.assertTrue(hasattr(__magic_name__							,    """width_multiplier"""				)				)







class 				__A					:





			def __init__(self							,    __magic_name__							,    __magic_name__=13							,    __magic_name__=64							,    __magic_name__=2							,    __magic_name__=3							,    __magic_name__="swish"							,    __magic_name__=3							,    __magic_name__=32							,    __magic_name__=0.1							,    __magic_name__=0.02							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=10							,    __magic_name__=None							,    __magic_name__=0.25							,    __magic_name__=0.0							,    __magic_name__=0.0							,    ):
						lowerCamelCase__ :      Optional[Any]								=		parent
						lowerCamelCase__ :      List[Any]								=		batch_size
						lowerCamelCase__ :      Optional[Any]								=		image_size
						lowerCamelCase__ :      Union[str, Any]								=		patch_size
						lowerCamelCase__ :      Dict								=		num_channels
						lowerCamelCase__ :      Optional[Any]								=		make_divisible(512 * width_multiplier							,    divisor=8				)
						lowerCamelCase__ :      str								=		hidden_act
						lowerCamelCase__ :      Union[str, Any]								=		conv_kernel_size
						lowerCamelCase__ :      int								=		output_stride
						lowerCamelCase__ :      Tuple								=		classifier_dropout_prob
						lowerCamelCase__ :      Optional[Any]								=		use_labels
						lowerCamelCase__ :      Tuple								=		is_training
						lowerCamelCase__ :      List[Any]								=		num_labels
						lowerCamelCase__ :      str								=		initializer_range
						lowerCamelCase__ :      Optional[Any]								=		scope
						lowerCamelCase__ :      Tuple								=		width_multiplier
						lowerCamelCase__ :      List[Any]								=		ffn_dropout
						lowerCamelCase__ :      Union[str, Any]								=		attn_dropout





			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

						lowerCamelCase__ :      str								=		None
						lowerCamelCase__ :      List[Any]								=		None
						if self.use_labels:
									lowerCamelCase__ :      Tuple								=		ids_tensor([self.batch_size]							,    self.num_labels				)
									lowerCamelCase__ :      List[Any]								=		ids_tensor([self.batch_size, self.image_size, self.image_size]							,    self.num_labels				)

						lowerCamelCase__ :      int								=		self.get_config()

						return config, pixel_values, labels, pixel_labels





			def        _snake_case    (self				):
						return MobileViTVaConfig(
						    image_size=self.image_size							,    patch_size=self.patch_size							,    num_channels=self.num_channels							,    hidden_act=self.hidden_act							,    conv_kernel_size=self.conv_kernel_size							,    output_stride=self.output_stride							,    classifier_dropout_prob=self.classifier_dropout_prob							,    initializer_range=self.initializer_range							,    width_multiplier=self.width_multiplier							,    ffn_dropout=self.ffn_dropout_prob							,    attn_dropout=self.attn_dropout_prob							,    )





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      Any								=		MobileViTVaModel(config=__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      Optional[Any]								=		model(__magic_name__				)
						self.parent.assertEqual(
						    result.last_hidden_state.shape							,    (
						        self.batch_size,
						        self.last_hidden_size,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )							,    )





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      List[str]								=		self.num_labels
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaForImageClassification(__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      Dict								=		model(__magic_name__							,    labels=__magic_name__				)
						self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      Dict								=		self.num_labels
						lowerCamelCase__ :      Any								=		MobileViTVaForSemanticSegmentation(__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      Optional[int]								=		model(__magic_name__				)
						self.parent.assertEqual(
						    result.logits.shape							,    (
						        self.batch_size,
						        self.num_labels,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )							,    )
						lowerCamelCase__ :      Dict								=		model(__magic_name__							,    labels=__magic_name__				)
						self.parent.assertEqual(
						    result.logits.shape							,    (
						        self.batch_size,
						        self.num_labels,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )							,    )





			def        _snake_case    (self				):
						lowerCamelCase__ :      Any								=		self.prepare_config_and_inputs()
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      List[str]								=		config_and_inputs
						lowerCamelCase__ :      str								=		{"""pixel_values""": pixel_values}
						return config, inputs_dict







@require_torch
class 				__A					( A_					, A_					, unittest.TestCase      ):
			UpperCamelCase					:Optional[Any]     =			(
			    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)

			UpperCamelCase					:List[Any]     =			(
			    {
			        '''feature-extraction''': MobileViTVaModel,
			        '''image-classification''': MobileViTVaForImageClassification,
			        '''image-segmentation''': MobileViTVaForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase					:List[Any]     =			False
			UpperCamelCase					:int     =			False
			UpperCamelCase					:Optional[int]     =			False
			UpperCamelCase					:int     =			False





			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaModelTester(self				)
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaConfigTester(self							,    config_class=__magic_name__							,    has_text_modality=__magic_name__				)





			def        _snake_case    (self				):
						self.config_tester.run_common_tests()





			@unittest.skip(reason="""MobileViTV2 does not use inputs_embeds"""				)
			def        _snake_case    (self				):
						pass





			@unittest.skip(reason="""MobileViTV2 does not support input and output embeddings"""				)
			def        _snake_case    (self				):
						pass





			@unittest.skip(reason="""MobileViTV2 does not output attentions"""				)
			def        _snake_case    (self				):
						pass





			@require_torch_multi_gpu
			@unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run."""				)
			def        _snake_case    (self				):
						pass





			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""				)
			def        _snake_case    (self				):
						pass





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									lowerCamelCase__ :      List[Any]								=		model_class(__magic_name__				)
									lowerCamelCase__ :      Optional[Any]								=		inspect.signature(model.forward				)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									lowerCamelCase__ :      Union[str, Any]								=		[*signature.parameters.keys()]

									lowerCamelCase__ :      Union[str, Any]								=		["""pixel_values"""]
									self.assertListEqual(arg_names[:1]							,    __magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      int								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__magic_name__				)





			def        _snake_case    (self				):
						def check_hidden_states_output(__magic_name__							,    __magic_name__							,    __magic_name__				):
									lowerCamelCase__ :      Dict								=		model_class(__magic_name__				)
									model.to(__magic_name__				)
									model.eval()

									with torch.no_grad():
												lowerCamelCase__ :      Optional[int]								=		model(**self._prepare_for_class(__magic_name__							,    __magic_name__				)				)

									lowerCamelCase__ :      str								=		outputs.hidden_states

									lowerCamelCase__ :      Dict								=		5
									self.assertEqual(len(__magic_name__				)							,    __magic_name__				)

									# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
									# with the width and height being successively divided by 2.
									lowerCamelCase__ :      Dict								=		2
									for i in range(len(__magic_name__				)				):
												self.assertListEqual(
												    list(hidden_states[i].shape[-2:]				)							,    [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]							,    )
												divisor *= 2

									self.assertEqual(self.model_tester.output_stride							,    divisor // 2				)

						lowerCamelCase__							,lowerCamelCase__ :      Optional[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									lowerCamelCase__ :      Any								=		True
									check_hidden_states_output(__magic_name__							,    __magic_name__							,    __magic_name__				)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									lowerCamelCase__ :      Tuple								=		True

									check_hidden_states_output(__magic_name__							,    __magic_name__							,    __magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      Tuple								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      List[Any]								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*__magic_name__				)





			@slow
			def        _snake_case    (self				):
						for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase__ :      int								=		MobileViTVaModel.from_pretrained(__magic_name__				)
									self.assertIsNotNone(__magic_name__				)







def      _A				()  ->List[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
			return image
@require_torch
@require_vision
class 				__A					( unittest.TestCase      ):





			@cached_property
			def        _snake_case    (self				):
						return (
						    MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""				)
						    if is_vision_available()
						    else None
						)





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      str								=		MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""				).to(
						    __magic_name__				)

						lowerCamelCase__ :      Union[str, Any]								=		self.default_image_processor
						lowerCamelCase__ :      Any								=		prepare_img()
						lowerCamelCase__ :      Optional[Any]								=		image_processor(images=__magic_name__							,    return_tensors="""pt"""				).to(__magic_name__				)

						# forward pass
						with torch.no_grad():
									lowerCamelCase__ :      List[str]								=		model(**__magic_name__				)

						# verify the logits
						lowerCamelCase__ :      List[Any]								=		torch.Size((1, 1000)				)
						self.assertEqual(outputs.logits.shape							,    __magic_name__				)

						lowerCamelCase__ :      Optional[Any]								=		torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]				).to(__magic_name__				)

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





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)
						lowerCamelCase__ :      Dict								=		model.to(__magic_name__				)

						lowerCamelCase__ :      str								=		MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)

						lowerCamelCase__ :      str								=		prepare_img()
						lowerCamelCase__ :      str								=		image_processor(images=__magic_name__							,    return_tensors="""pt"""				).to(__magic_name__				)

						# forward pass
						with torch.no_grad():
									lowerCamelCase__ :      Dict								=		model(**__magic_name__				)
						lowerCamelCase__ :      List[str]								=		outputs.logits

						# verify the logits
						lowerCamelCase__ :      Tuple								=		torch.Size((1, 21, 32, 32)				)
						self.assertEqual(logits.shape							,    __magic_name__				)

						lowerCamelCase__ :      Any								=		torch.tensor(
						    [
						        [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
						        [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
						        [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
						    ]							,    device=__magic_name__							,    )

						self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,    __magic_name__							,    atol=1E-4				)				)





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      Union[str, Any]								=		MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)
						lowerCamelCase__ :      List[Any]								=		model.to(__magic_name__				)

						lowerCamelCase__ :      Optional[int]								=		MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)

						lowerCamelCase__ :      Union[str, Any]								=		prepare_img()
						lowerCamelCase__ :      Dict								=		image_processor(images=__magic_name__							,    return_tensors="""pt"""				).to(__magic_name__				)

						# forward pass
						with torch.no_grad():
									lowerCamelCase__ :      List[str]								=		model(**__magic_name__				)

						lowerCamelCase__ :      str								=		outputs.logits.detach().cpu()

						lowerCamelCase__ :      Optional[int]								=		image_processor.post_process_semantic_segmentation(outputs=__magic_name__							,    target_sizes=[(50, 60)]				)
						lowerCamelCase__ :      List[Any]								=		torch.Size((50, 60)				)
						self.assertEqual(segmentation[0].shape							,    __magic_name__				)

						lowerCamelCase__ :      List[str]								=		image_processor.post_process_semantic_segmentation(outputs=__magic_name__				)
						lowerCamelCase__ :      int								=		torch.Size((32, 32)				)
						self.assertEqual(segmentation[0].shape							,    __magic_name__				)



