
'''simple docstring'''
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 			SCREAMING_SNAKE_CASE__      (     snake_case_):







				def 						UpperCAmelCase_    (       self     )->		Tuple:







											'''simple docstring'''






											UpperCamelCase   			=     self.config_class(**self.inputs_dict     )
											self.parent.assertTrue(hasattr(A_						,				'width_multiplier'     )     )


class 			SCREAMING_SNAKE_CASE__      :







				def __init__(       self						,				A_						,				A_=13						,				A_=64						,				A_=2						,				A_=3						,				A_="swish"						,				A_=3						,				A_=32						,				A_=0.1						,				A_=0.02						,				A_=True						,				A_=True						,				A_=10						,				A_=None						,				A_=0.25						,				A_=0.0						,				A_=0.0						,				)->		Dict:







											'''simple docstring'''






											UpperCamelCase   			=     parent
											UpperCamelCase   			=     batch_size
											UpperCamelCase   			=     image_size
											UpperCamelCase   			=     patch_size
											UpperCamelCase   			=     num_channels
											UpperCamelCase   			=     make_divisible(512 * width_multiplier						,				divisor=8     )
											UpperCamelCase   			=     hidden_act
											UpperCamelCase   			=     conv_kernel_size
											UpperCamelCase   			=     output_stride
											UpperCamelCase   			=     classifier_dropout_prob
											UpperCamelCase   			=     use_labels
											UpperCamelCase   			=     is_training
											UpperCamelCase   			=     num_labels
											UpperCamelCase   			=     initializer_range
											UpperCamelCase   			=     scope
											UpperCamelCase   			=     width_multiplier
											UpperCamelCase   			=     ffn_dropout
											UpperCamelCase   			=     attn_dropout







				def 						UpperCAmelCase_    (       self     )->		Dict:







											'''simple docstring'''






											UpperCamelCase   			=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

											UpperCamelCase   			=     None
											UpperCamelCase   			=     None
											if self.use_labels:
																		UpperCamelCase   			=     ids_tensor([self.batch_size]						,				self.num_labels     )
																		UpperCamelCase   			=     ids_tensor([self.batch_size, self.image_size, self.image_size]						,				self.num_labels     )

											UpperCamelCase   			=     self.get_config()

											return config, pixel_values, labels, pixel_labels







				def 						UpperCAmelCase_    (       self     )->		str:







											'''simple docstring'''






											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 						UpperCAmelCase_    (       self						,				A_						,				A_						,				A_						,				A_     )->		List[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     MobileViTVaModel(config=A_     )
											model.to(A_     )
											model.eval()
											UpperCamelCase   			=     model(A_     )
											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 						UpperCAmelCase_    (       self						,				A_						,				A_						,				A_						,				A_     )->		Optional[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     self.num_labels
											UpperCamelCase   			=     MobileViTVaForImageClassification(A_     )
											model.to(A_     )
											model.eval()
											UpperCamelCase   			=     model(A_						,				labels=A_     )
											self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)     )







				def 						UpperCAmelCase_    (       self						,				A_						,				A_						,				A_						,				A_     )->		Dict:







											'''simple docstring'''






											UpperCamelCase   			=     self.num_labels
											UpperCamelCase   			=     MobileViTVaForSemanticSegmentation(A_     )
											model.to(A_     )
											model.eval()
											UpperCamelCase   			=     model(A_     )
											self.parent.assertEqual(
											    result.logits.shape						,				(
											        self.batch_size,
											        self.num_labels,
											        self.image_size // self.output_stride,
											        self.image_size // self.output_stride,
											    )						,				)
											UpperCamelCase   			=     model(A_						,				labels=A_     )
											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 						UpperCAmelCase_    (       self     )->		str:







											'''simple docstring'''






											UpperCamelCase   			=     self.prepare_config_and_inputs()
											UpperCamelCase			,	UpperCamelCase			,	UpperCamelCase			,	UpperCamelCase   			=     config_and_inputs
											UpperCamelCase   			=     {'pixel_values': pixel_values}
											return config, inputs_dict


@require_torch
class 			SCREAMING_SNAKE_CASE__      (     snake_case_							,       snake_case_							,       unittest.TestCase):
				lowerCAmelCase_     			=							(
				    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)

				lowerCAmelCase_     			=							(
				    {
				        """feature-extraction""": MobileViTVaModel,
				        """image-classification""": MobileViTVaForImageClassification,
				        """image-segmentation""": MobileViTVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				lowerCAmelCase_     			=							False
				lowerCAmelCase_     			=							False
				lowerCAmelCase_     			=							False
				lowerCAmelCase_     			=							False







				def 						UpperCAmelCase_    (       self     )->		int:







											'''simple docstring'''






											UpperCamelCase   			=     MobileViTVaModelTester(self     )
											UpperCamelCase   			=     MobileViTVaConfigTester(self						,				config_class=A_						,				has_text_modality=A_     )







				def 						UpperCAmelCase_    (       self     )->		str:







											'''simple docstring'''






											self.config_tester.run_common_tests()







				@unittest.skip(reason='MobileViTV2 does not use inputs_embeds'     )
				def 						UpperCAmelCase_    (       self     )->		Optional[int]:







											'''simple docstring'''






											pass







				@unittest.skip(reason='MobileViTV2 does not support input and output embeddings'     )
				def 						UpperCAmelCase_    (       self     )->		List[Any]:







											'''simple docstring'''






											pass







				@unittest.skip(reason='MobileViTV2 does not output attentions'     )
				def 						UpperCAmelCase_    (       self     )->		List[str]:







											'''simple docstring'''






											pass







				@require_torch_multi_gpu
				@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'     )
				def 						UpperCAmelCase_    (       self     )->		str:







											'''simple docstring'''






											pass







				@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'     )
				def 						UpperCAmelCase_    (       self     )->		Dict:







											'''simple docstring'''






											pass







				def 						UpperCAmelCase_    (       self     )->		int:







											'''simple docstring'''






											UpperCamelCase			,	UpperCamelCase   			=     self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		UpperCamelCase   			=     model_class(A_     )
																		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]						,				A_     )







				def 						UpperCAmelCase_    (       self     )->		Optional[int]:







											'''simple docstring'''






											UpperCamelCase   			=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*A_     )







				def 						UpperCAmelCase_    (       self     )->		Dict:







											'''simple docstring'''






											def check_hidden_states_output(A_						,				A_						,				A_     ):
																		UpperCamelCase   			=     model_class(A_     )
																		model.to(A_     )
																		model.eval()

																		with torch.no_grad():
																									UpperCamelCase   			=     model(**self._prepare_for_class(A_						,				A_     )     )

																		UpperCamelCase   			=     outputs.hidden_states

																		UpperCamelCase   			=     5
																		self.assertEqual(len(A_     )						,				A_     )

																		# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
																		# with the width and height being successively divided by 2.
																		UpperCamelCase   			=     2
																		for i in range(len(A_     )     ):
																									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     )

											UpperCamelCase			,	UpperCamelCase   			=     self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		UpperCamelCase   			=     True
																		check_hidden_states_output(A_						,				A_						,				A_     )

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		UpperCamelCase   			=     True

																		check_hidden_states_output(A_						,				A_						,				A_     )







				def 						UpperCAmelCase_    (       self     )->		Optional[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*A_     )







				def 						UpperCAmelCase_    (       self     )->		Tuple:







											'''simple docstring'''






											UpperCamelCase   			=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*A_     )







				@slow
				def 						UpperCAmelCase_    (       self     )->		Optional[int]:







											'''simple docstring'''






											for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCamelCase   			=     MobileViTVaModel.from_pretrained(A_     )
																		self.assertIsNotNone(A_     )







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





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







				@cached_property
				def 						UpperCAmelCase_    (       self     )->		Union[str, Any]:







											'''simple docstring'''






											return (
											    MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'     )
											    if is_vision_available()
											    else None
											)







				@slow
				def 						UpperCAmelCase_    (       self     )->		List[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'     ).to(
											    A_     )

											UpperCamelCase   			=     self.default_image_processor
											UpperCamelCase   			=     prepare_img()
											UpperCamelCase   			=     image_processor(images=A_						,				return_tensors='pt'     ).to(A_     )

											# forward pass
											with torch.no_grad():
																		UpperCamelCase   			=     model(**A_     )

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

											UpperCamelCase   			=     torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01]     ).to(A_     )

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







				@slow
				def 						UpperCAmelCase_    (       self     )->		Optional[int]:







											'''simple docstring'''






											UpperCamelCase   			=     MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'     )
											UpperCamelCase   			=     model.to(A_     )

											UpperCamelCase   			=     MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'     )

											UpperCamelCase   			=     prepare_img()
											UpperCamelCase   			=     image_processor(images=A_						,				return_tensors='pt'     ).to(A_     )

											# forward pass
											with torch.no_grad():
																		UpperCamelCase   			=     model(**A_     )
											UpperCamelCase   			=     outputs.logits

											# verify the logits
											UpperCamelCase   			=     torch.Size((1, 21, 32, 32)     )
											self.assertEqual(logits.shape						,				A_     )

											UpperCamelCase   			=     torch.tensor(
											    [
											        [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
											        [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
											        [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
											    ]						,				device=A_						,				)

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







				@slow
				def 						UpperCAmelCase_    (       self     )->		int:







											'''simple docstring'''






											UpperCamelCase   			=     MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'     )
											UpperCamelCase   			=     model.to(A_     )

											UpperCamelCase   			=     MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'     )

											UpperCamelCase   			=     prepare_img()
											UpperCamelCase   			=     image_processor(images=A_						,				return_tensors='pt'     ).to(A_     )

											# forward pass
											with torch.no_grad():
																		UpperCamelCase   			=     model(**A_     )

											UpperCamelCase   			=     outputs.logits.detach().cpu()

											UpperCamelCase   			=     image_processor.post_process_semantic_segmentation(outputs=A_						,				target_sizes=[(50, 60)]     )
											UpperCamelCase   			=     torch.Size((50, 60)     )
											self.assertEqual(segmentation[0].shape						,				A_     )

											UpperCamelCase   			=     image_processor.post_process_semantic_segmentation(outputs=A_     )
											UpperCamelCase   			=     torch.Size((32, 32)     )
											self.assertEqual(segmentation[0].shape						,				A_     )






'''simple docstring'''
import uuid
from typing import Any, Dict, List, Optional, Union

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

if is_torch_available():
						import torch


lowerCAmelCase					:    Optional[Any]           = logging.get_logger(__name__)


class 			SCREAMING_SNAKE_CASE__      :







				def __init__(       self						,				A_ = None						,				A_ = None						,				A_=None						,				A_=None     )->		Optional[Any]:







											'''simple docstring'''






											if not conversation_id:
																		UpperCamelCase   			=     uuid.uuida()
											if past_user_inputs is None:
																		UpperCamelCase   			=     []
											if generated_responses is None:
																		UpperCamelCase   			=     []

											UpperCamelCase   			=     conversation_id
											UpperCamelCase   			=     past_user_inputs
											UpperCamelCase   			=     generated_responses
											UpperCamelCase   			=     text







				def __eq__(       self						,				A_     )->		List[Any]:







											'''simple docstring'''






											if not isinstance(A_						,				A_     ):
																		return False
											if self.uuid == other.uuid:
																		return True
											return (
											    self.new_user_input == other.new_user_input
											    and self.past_user_inputs == other.past_user_inputs
											    and self.generated_responses == other.generated_responses
											)







				def 						UpperCAmelCase_    (       self						,				A_						,				A_ = False     )->		int:







											'''simple docstring'''






											if self.new_user_input:
																		if overwrite:
																									logger.warning(
																									    F'''User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '''
																									    F'''with: "{text}".'''     )
																									UpperCamelCase   			=     text
																		else:
																									logger.warning(
																									    F'''User input added while unprocessed input was existing: "{self.new_user_input}" new input '''
																									    F'''ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input'''     )
											else:
																		UpperCamelCase   			=     text







				def 						UpperCAmelCase_    (       self     )->		Any:







											'''simple docstring'''






											if self.new_user_input:
																		self.past_user_inputs.append(self.new_user_input     )
											UpperCamelCase   			=     None







				def 						UpperCAmelCase_    (       self						,				A_     )->		int:







											'''simple docstring'''






											self.generated_responses.append(A_     )







				def 						UpperCAmelCase_    (       self     )->		List[str]:







											'''simple docstring'''






											for user_input, generated_response in zip(self.past_user_inputs						,				self.generated_responses     ):
																		yield True, user_input
																		yield False, generated_response
											if self.new_user_input:
																		yield True, self.new_user_input







				def __repr__(       self     )->		Any:







											'''simple docstring'''






											UpperCamelCase   			=     F'''Conversation id: {self.uuid} \n'''
											for is_user, text in self.iter_texts():
																		UpperCamelCase   			=     'user' if is_user else 'bot'
																		output += F'''{name} >> {text} \n'''
											return output


@add_end_docstrings(
    snake_case_							,       R"""
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    """							,       )
class 			SCREAMING_SNAKE_CASE__      (     snake_case_):







				def __init__(       self						,				*A_						,				**A_     )->		Any:







											'''simple docstring'''






											super().__init__(*A_						,				**A_     )
											if self.tokenizer.pad_token_id is None:
																		UpperCamelCase   			=     self.tokenizer.eos_token







				def 						UpperCAmelCase_    (       self						,				A_=None						,				A_=None						,				A_=None						,				**A_     )->		Union[str, Any]:







											'''simple docstring'''






											UpperCamelCase   			=     {}
											UpperCamelCase   			=     {}
											UpperCamelCase   			=     {}

											if min_length_for_response is not None:
																		UpperCamelCase   			=     min_length_for_response
											if minimum_tokens is not None:
																		UpperCamelCase   			=     minimum_tokens

											if "max_length" in generate_kwargs:
																		UpperCamelCase   			=     generate_kwargs['max_length']
																		# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
											if clean_up_tokenization_spaces is not None:
																		UpperCamelCase   			=     clean_up_tokenization_spaces

											if generate_kwargs:
																		forward_params.update(A_     )
											return preprocess_params, forward_params, postprocess_params







				def __call__(       self						,				A_						,				A_=0						,				**A_     )->		Any:







											'''simple docstring'''






											UpperCamelCase   			=     super().__call__(A_						,				num_workers=A_						,				**A_     )
											if isinstance(A_						,				A_     ) and len(A_     ) == 1:
																		return outputs[0]
											return outputs







				def 						UpperCAmelCase_    (       self						,				A_						,				A_=32     )->		Dict[str, Any]:







											'''simple docstring'''






											if not isinstance(A_						,				A_     ):
																		raise ValueError('ConversationalPipeline, expects Conversation as inputs'     )
											if conversation.new_user_input is None:
																		raise ValueError(
																		    F'''Conversation with UUID {type(conversation.uuid     )} does not contain new user input to process. '''
																		    'Add user inputs with the conversation\'s `add_user_input` method'     )
											if hasattr(self.tokenizer						,				'_build_conversation_input_ids'     ):
																		UpperCamelCase   			=     self.tokenizer._build_conversation_input_ids(A_     )
											else:
																		# If the tokenizer cannot handle conversations, we default to only the old version
																		UpperCamelCase   			=     self._legacy_parse_and_tokenize(A_     )

											if self.framework == "pt":
																		UpperCamelCase   			=     torch.LongTensor([input_ids]     )
											elif self.framework == "tf":
																		UpperCamelCase   			=     tf.constant([input_ids]     )
											return {"input_ids": input_ids, "conversation": conversation}







				def 						UpperCAmelCase_    (       self						,				A_						,				A_=10						,				**A_     )->		Optional[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     generate_kwargs.get('max_length'						,				self.model.config.max_length     )

											UpperCamelCase   			=     model_inputs['input_ids'].shape[1]
											if max_length - minimum_tokens < n:
																		logger.warning(F'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})'''     )
																		UpperCamelCase   			=     max_length - minimum_tokens
																		UpperCamelCase   			=     model_inputs['input_ids'][:, -trim:]
																		if "attention_mask" in model_inputs:
																									UpperCamelCase   			=     model_inputs['attention_mask'][:, -trim:]
											UpperCamelCase   			=     model_inputs.pop('conversation'     )
											UpperCamelCase   			=     max_length
											UpperCamelCase   			=     self.model.generate(**A_						,				**A_     )
											if self.model.config.is_encoder_decoder:
																		UpperCamelCase   			=     1
											else:
																		UpperCamelCase   			=     n
											return {"output_ids": output_ids[:, start_position:], "conversation": conversation}







				def 						UpperCAmelCase_    (       self						,				A_						,				A_=True     )->		Tuple:







											'''simple docstring'''






											UpperCamelCase   			=     model_outputs['output_ids']
											UpperCamelCase   			=     self.tokenizer.decode(
											    output_ids[0]						,				skip_special_tokens=A_						,				clean_up_tokenization_spaces=A_						,				)
											UpperCamelCase   			=     model_outputs['conversation']
											conversation.mark_processed()
											conversation.append_response(A_     )
											return conversation







				def 						UpperCAmelCase_    (       self						,				A_     )->		Dict:







											'''simple docstring'''






											UpperCamelCase   			=     self.tokenizer.eos_token_id
											UpperCamelCase   			=     []
											for is_user, text in conversation.iter_texts():
																		if eos_token_id is not None:
																									input_ids.extend(self.tokenizer.encode(A_						,				add_special_tokens=A_     ) + [eos_token_id]     )
																		else:
																									input_ids.extend(self.tokenizer.encode(A_						,				add_special_tokens=A_     )     )

											if len(A_     ) > self.tokenizer.model_max_length:
																		UpperCamelCase   			=     input_ids[-self.tokenizer.model_max_length :]
											return input_ids




