




'''simple docstring'''





from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor




class  _snake_case		:




			def __init__(					self				,							a__				,							a__=13				,							a__=30				,							a__=2				,							a__=3				,							a__=True				,							a__=True				,							a__=32				,							a__=2				,							a__=4				,							a__=37				,							a__="gelu"				,							a__=0.1				,							a__=0.1				,							a__=10				,							a__=0.0_2				,							a__=3				,							a__=None				,							)				->				Optional[Any]:

										'''simple docstring'''




										snake_case_						=      parent
										snake_case_						=      batch_size
										snake_case_						=      image_size
										snake_case_						=      patch_size
										snake_case_						=      num_channels
										snake_case_						=      is_training
										snake_case_						=      use_labels
										snake_case_						=      hidden_size
										snake_case_						=      num_hidden_layers
										snake_case_						=      num_attention_heads
										snake_case_						=      intermediate_size
										snake_case_						=      hidden_act
										snake_case_						=      hidden_dropout_prob
										snake_case_						=      attention_probs_dropout_prob
										snake_case_						=      type_sequence_label_size
										snake_case_						=      initializer_range
										snake_case_						=      scope

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




			def    lowerCAmelCase__				(					self							)				->				Tuple:

										'''simple docstring'''




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

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

										snake_case_						=      self.get_config()

										return config, pixel_values, labels




			def    lowerCAmelCase__				(					self							)				->				Union[str, Any]:

										'''simple docstring'''




										return ViTConfig(
										    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				,							is_decoder=A__				,							initializer_range=self.initializer_range				,							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__							)				->				Dict:

										'''simple docstring'''




										snake_case_						=      TFViTModel(config=A__							)
										snake_case_						=      model(A__				,							training=A__							)
										self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)							)

										# Test with an image with different size than the one specified in config.
										snake_case_						=      self.image_size // 2
										snake_case_						=      pixel_values[:, :, :image_size, :image_size]
										snake_case_						=      model(A__				,							interpolate_pos_encoding=A__				,							training=A__							)
										snake_case_						=      (image_size // self.patch_size) ** 2 + 1
										self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, seq_length, self.hidden_size)							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__							)				->				List[Any]:

										'''simple docstring'''




										snake_case_						=      self.type_sequence_label_size
										snake_case_						=      TFViTForImageClassification(A__							)
										snake_case_						=      model(A__				,							labels=A__				,							training=A__							)
										self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)							)

										# Test with an image with different size than the one specified in config.
										snake_case_						=      self.image_size // 2
										snake_case_						=      pixel_values[:, :, :image_size, :image_size]
										snake_case_						=      model(A__				,							interpolate_pos_encoding=A__				,							training=A__							)
										self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)							)

										# test greyscale images
										snake_case_						=      1
										snake_case_						=      TFViTForImageClassification(A__							)
										snake_case_						=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
										snake_case_						=      model(A__							)
										self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)							)




			def    lowerCAmelCase__				(					self							)				->				List[Any]:

										'''simple docstring'''




										snake_case_						=      self.prepare_config_and_inputs()
										snake_case_						=      config_and_inputs
										snake_case_						=      {"""pixel_values""": pixel_values}
										return config, inputs_dict




@require_tf
class  _snake_case		(	lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_     :      List[str]						       =    (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
			lowerCAmelCase_     :      List[str]						       =    (
			    {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCAmelCase_     :      List[Any]						       =    False
			lowerCAmelCase_     :      List[Any]						       =    False
			lowerCAmelCase_     :      Union[str, Any]						       =    False




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

										'''simple docstring'''




										snake_case_						=      TFViTModelTester(self							)
										snake_case_						=      ConfigTester(self				,							config_class=A__				,							has_text_modality=A__				,							hidden_size=37							)




			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




										self.config_tester.run_common_tests()




			@unittest.skip(reason="ViT does not use inputs_embeds"							)
			def    lowerCAmelCase__				(					self							)				->				Optional[Any]:

										'''simple docstring'''




										pass




			@unittest.skip(reason="ViT does not use inputs_embeds"							)
			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




										pass




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	snake_case_						=      model_class(A__							)
																	self.assertIsInstance(model.get_input_embeddings()				,							(tf.keras.layers.Layer)							)
																	snake_case_						=      model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(A__				,							tf.keras.layers.Layer							)							)




			def    lowerCAmelCase__				(					self							)				->				Union[str, Any]:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs_for_common()

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

																	snake_case_						=      ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]				,							A__							)




			def    lowerCAmelCase__				(					self							)				->				Any:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*A__							)




			def    lowerCAmelCase__				(					self							)				->				List[Any]:

										'''simple docstring'''




										snake_case_						=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*A__							)




			@slow
			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										snake_case_						=      TFViTModel.from_pretrained("google/vit-base-patch16-224"							)
										self.assertIsNotNone(A__							)


def      UpperCamelCase_(	):

							'''simple docstring'''






							snake_case_						=      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
							return image




@require_tf
@require_vision
class  _snake_case		(	unittest.TestCase							):




			@cached_property
			def    lowerCAmelCase__				(					self							)				->				Any:

										'''simple docstring'''




										return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"							) if is_vision_available() else None




			@slow
			def    lowerCAmelCase__				(					self							)				->				Any:

										'''simple docstring'''




										snake_case_						=      TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"							)

										snake_case_						=      self.default_image_processor
										snake_case_						=      prepare_img()
										snake_case_						=      image_processor(images=A__				,							return_tensors="tf"							)

										# forward pass
										snake_case_						=      model(**A__							)

										# verify the logits
										snake_case_						=      tf.TensorShape((1, 1_000)							)
										self.assertEqual(outputs.logits.shape				,							A__							)

										snake_case_						=      tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]							)

										tf.debugging.assert_near(outputs.logits[0, :3]				,							A__				,							atol=1e-4							)







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


A_       : List[Any]         =			logging.get_logger(__name__)



class     _a						:


					'''simple docstring'''






					def __init__( self    ,       A__ = None    ,       A__ = None    ,       A__=None    ,       A__=None			):
						if not conversation_id:
							A__							:    List[Any]        =		uuid.uuida()
						if past_user_inputs is None:
							A__							:    Dict        =		[]
						if generated_responses is None:
							A__							:    int        =		[]

						A__							:    uuid.UUID        =		conversation_id
						A__							:    List[str]        =		past_user_inputs
						A__							:    List[str]        =		generated_responses
						A__							:    Optional[str]        =		text






					def __eq__( self    ,       A__			):
						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   __A			( self    ,       A__    ,       A__ = False			):
						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}\"."""			)
								A__							:    str        =		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:
							A__							:    Tuple        =		text






					def   __A			( self			):
						if self.new_user_input:
							self.past_user_inputs.append(self.new_user_input			)
						A__							:    Tuple        =		None






					def   __A			( self    ,       A__			):
						self.generated_responses.append(A__			)






					def   __A			( self			):
						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			):
						A__							:    Optional[Any]        =		F"""Conversation id: {self.uuid} \n"""
						for is_user, text in self.iter_texts():
							A__							:    str        =		"""user""" if is_user else """bot"""
							output += F"""{name} >> {text} \n"""
						return output



@add_end_docstrings(
    __magic_name__		,   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     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self    ,       *A__    ,       **A__			):
						super().__init__(*A__    ,       **A__			)
						if self.tokenizer.pad_token_id is None:
							A__							:    Tuple        =		self.tokenizer.eos_token






					def   __A			( self    ,       A__=None    ,       A__=None    ,       A__=None    ,       **A__			):
						A__							:    Tuple        =		{}
						A__							:    List[str]        =		{}
						A__							:    Union[str, Any]        =		{}

						if min_length_for_response is not None:
							A__							:    str        =		min_length_for_response
						if minimum_tokens is not None:
							A__							:    List[str]        =		minimum_tokens

						if "max_length" in generate_kwargs:
							A__							:    List[Any]        =		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:
							A__							:    Optional[int]        =		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__			):
						A__							:    Optional[Any]        =		super().__call__(A__    ,       num_workers=A__    ,       **A__			)
						if isinstance(A__    ,       A__			) and len(A__			) == 1:
							return outputs[0]
						return outputs






					def   __A			( self    ,       A__    ,       A__=32			):
						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"""			):
							A__							:    List[str]        =		self.tokenizer._build_conversation_input_ids(A__			)
						else:
							# If the tokenizer cannot handle conversations, we default to only the old version
							A__							:    Tuple        =		self._legacy_parse_and_tokenize(A__			)

						if self.framework == "pt":
							A__							:    List[str]        =		torch.LongTensor([input_ids]			)
						elif self.framework == "tf":
							A__							:    Optional[Any]        =		tf.constant([input_ids]			)
						return {"input_ids": input_ids, "conversation": conversation}






					def   __A			( self    ,       A__    ,       A__=10    ,       **A__			):
						A__							:    List[Any]        =		generate_kwargs.get("""max_length"""    ,       self.model.config.max_length			)

						A__							:    Optional[int]        =		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})"""			)
							A__							:    Dict        =		max_length - minimum_tokens
							A__							:    Optional[int]        =		model_inputs["""input_ids"""][:, -trim:]
							if "attention_mask" in model_inputs:
								A__							:    str        =		model_inputs["""attention_mask"""][:, -trim:]
						A__							:    List[str]        =		model_inputs.pop("""conversation"""			)
						A__							:    Dict        =		max_length
						A__							:    str        =		self.model.generate(**A__    ,       **A__			)
						if self.model.config.is_encoder_decoder:
							A__							:    Union[str, Any]        =		1
						else:
							A__							:    Optional[Any]        =		n
						return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






					def   __A			( self    ,       A__    ,       A__=True			):
						A__							:    Dict        =		model_outputs["""output_ids"""]
						A__							:    str        =		self.tokenizer.decode(
						    output_ids[0]    ,       skip_special_tokens=A__    ,       clean_up_tokenization_spaces=A__    ,       )
						A__							:    Optional[int]        =		model_outputs["""conversation"""]
						conversation.mark_processed()
						conversation.append_response(A__			)
						return conversation






					def   __A			( self    ,       A__			):
						A__							:    str        =		self.tokenizer.eos_token_id
						A__							:    Tuple        =		[]
						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:
							A__							:    str        =		input_ids[-self.tokenizer.model_max_length :]
						return input_ids



