
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
		from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class  lowerCamelCase__							:




	'''simple docstring'''




	def __init__(					self		:List[Any]     ,   a		:Dict     ,   a		:Any=3     ,   a		:Any=3_2     ,   a		:Optional[Any]=3     ,   a		:str=1_0     ,   a		:Union[str, Any]=[1_0, 2_0, 3_0, 4_0]     ,   a		:Optional[Any]=[1, 1, 2, 1]     ,   a		:Optional[Any]=True     ,   a		:Dict=True     ,   a		:Tuple="relu"     ,   a		:List[str]=3     ,   a		:Tuple=None     ,   )		-> Tuple:
								__UpperCamelCase	:   Optional[Any]			   =					parent
								__UpperCamelCase	:   Dict			   =					batch_size
								__UpperCamelCase	:   int			   =					image_size
								__UpperCamelCase	:   Dict			   =					num_channels
								__UpperCamelCase	:   Optional[int]			   =					embeddings_size
								__UpperCamelCase	:   List[Any]			   =					hidden_sizes
								__UpperCamelCase	:   Optional[Any]			   =					depths
								__UpperCamelCase	:   Optional[int]			   =					is_training
								__UpperCamelCase	:   Union[str, Any]			   =					use_labels
								__UpperCamelCase	:   Optional[int]			   =					hidden_act
								__UpperCamelCase	:   Tuple			   =					num_labels
								__UpperCamelCase	:   Tuple			   =					scope
								__UpperCamelCase	:   Dict			   =					len(a						)







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Any:
								__UpperCamelCase	:   List[str]			   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

								__UpperCamelCase	:   List[Any]			   =					self.get_config()

								return config, pixel_values, labels







	def    _lowerCamelCase				(					self		:Union[str, Any]						)		-> int:
								return ResNetConfig(
								    num_channels=self.num_channels     ,   embeddings_size=self.embeddings_size     ,   hidden_sizes=self.hidden_sizes     ,   depths=self.depths     ,   hidden_act=self.hidden_act     ,   num_labels=self.num_labels     ,   image_size=self.image_size     ,   )







	def    _lowerCamelCase				(					self		:List[Any]     ,   a		:Dict     ,   a		:int     ,   a		:Optional[Any]						)		-> Tuple:
								__UpperCamelCase	:   str			   =					TFResNetModel(config=a						)
								__UpperCamelCase	:   Union[str, Any]			   =					model(a						)
								# expected last hidden states: B, C, H // 32, W // 32
								self.parent.assertEqual(
								    result.last_hidden_state.shape     ,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)     ,   )







	def    _lowerCamelCase				(					self		:Union[str, Any]     ,   a		:Optional[int]     ,   a		:List[str]     ,   a		:Optional[Any]						)		-> Any:
								__UpperCamelCase	:   str			   =					self.num_labels
								__UpperCamelCase	:   Optional[int]			   =					TFResNetForImageClassification(a						)
								__UpperCamelCase	:   List[str]			   =					model(a     ,   labels=a						)
								self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.num_labels)						)







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> List[str]:
								__UpperCamelCase	:   Optional[int]			   =					self.prepare_config_and_inputs()
								__UpperCamelCase   ,						__UpperCamelCase   ,						__UpperCamelCase	:   Union[str, Any]			   =					config_and_inputs
								__UpperCamelCase	:   List[str]			   =					{"pixel_values": pixel_values}
								return config, inputs_dict




@require_tf
class  lowerCamelCase__							(				__lowercase     ,						__lowercase     ,						unittest.TestCase):




	'''simple docstring'''




	_A								=     (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	_A								=     (
	    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	_A								=     False
	_A								=     False
	_A								=     False
	_A								=     False
	_A								=     False







	def    _lowerCamelCase				(					self		:int						)		-> List[str]:
								__UpperCamelCase	:   Union[str, Any]			   =					TFResNetModelTester(self						)
								__UpperCamelCase	:   List[Any]			   =					ConfigTester(self     ,   config_class=a     ,   has_text_modality=a						)







	def    _lowerCamelCase				(					self		:int						)		-> Dict:
								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()







	def    _lowerCamelCase				(					self		:str						)		-> Optional[Any]:
								return







	@unittest.skip(reason="ResNet does not use inputs_embeds"						)
	def    _lowerCamelCase				(					self		:Tuple						)		-> Tuple:
								pass







	@unittest.skip(reason="ResNet does not support input and output embeddings"						)
	def    _lowerCamelCase				(					self		:List[Any]						)		-> List[str]:
								pass







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Tuple:
								__UpperCamelCase   ,						__UpperCamelCase	:   Union[str, Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															__UpperCamelCase	:   Dict			   =					model_class(a						)
															__UpperCamelCase	:   Union[str, Any]			   =					inspect.signature(model.call						)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															__UpperCamelCase	:   Dict			   =					[*signature.parameters.keys()]

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







	def    _lowerCamelCase				(					self		:List[str]						)		-> List[str]:
								__UpperCamelCase	:   Union[str, Any]			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a						)







	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> Tuple:
								def check_hidden_states_output(a		:Optional[Any]     ,   a		:Optional[int]     ,   a		:List[str]						):
															__UpperCamelCase	:   int			   =					model_class(a						)
															__UpperCamelCase	:   int			   =					model(**self._prepare_for_class(a     ,   a						)						)

															__UpperCamelCase	:   Optional[Any]			   =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															__UpperCamelCase	:   Optional[int]			   =					self.model_tester.num_stages
															self.assertEqual(len(a						)     ,   expected_num_stages + 1						)

															# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]						)     ,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]     ,   )

								__UpperCamelCase   ,						__UpperCamelCase	:   Optional[Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()
								__UpperCamelCase	:   str			   =					["basic", "bottleneck"]
								for model_class in self.all_model_classes:
															for layer_type in layers_type:
																						__UpperCamelCase	:   int			   =					layer_type
																						__UpperCamelCase	:   int			   =					True
																						check_hidden_states_output(a     ,   a     ,   a						)

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

																						check_hidden_states_output(a     ,   a     ,   a						)







	def    _lowerCamelCase				(					self		:Union[str, Any]						)		-> Dict:
								__UpperCamelCase	:   int			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a						)







	@slow
	def    _lowerCamelCase				(					self		:Dict						)		-> Dict:
								for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															__UpperCamelCase	:   Optional[Any]			   =					TFResNetModel.from_pretrained(a						)
															self.assertIsNotNone(a						)




def 	_SCREAMING_SNAKE_CASE					(		)					->    int:






							'''simple docstring'''





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




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




	'''simple docstring'''




	@cached_property
	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> Tuple:
								return (
								    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
								    if is_vision_available()
								    else None
								)







	@slow
	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Optional[int]:
								__UpperCamelCase	:   int			   =					TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

								__UpperCamelCase	:   List[Any]			   =					self.default_image_processor
								__UpperCamelCase	:   List[str]			   =					prepare_img()
								__UpperCamelCase	:   List[str]			   =					image_processor(images=a     ,   return_tensors="tf"						)

								# forward pass
								__UpperCamelCase	:   Dict			   =					model(**a						)

								# verify the logits
								__UpperCamelCase	:   Dict			   =					tf.TensorShape((1, 1_0_0_0)						)
								self.assertEqual(outputs.logits.shape     ,   a						)

								__UpperCamelCase	:   Union[str, Any]			   =					tf.constant([-11.1069, -9.7877, -8.3777]						)

								self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,   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


lowercase  :					List[str]													=       logging.get_logger(__name__)




class  lowerCamelCase__							:




	'''simple docstring'''




	def __init__(					self		:str     ,   a		:str = None     ,   a		:uuid.UUID = None     ,   a		:Tuple=None     ,   a		:Optional[Any]=None						)		-> str:
								if not conversation_id:
															__UpperCamelCase	:   Dict			   =					uuid.uuida()
								if past_user_inputs is None:
															__UpperCamelCase	:   List[Any]			   =					[]
								if generated_responses is None:
															__UpperCamelCase	:   Any			   =					[]

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







	def __eq__(					self		:Optional[int]     ,   a		:Optional[int]						)		-> Union[str, Any]:
								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    _lowerCamelCase				(					self		:Optional[int]     ,   a		:str     ,   a		:bool = False						)		-> str:
								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	:   Any			   =					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	:   int			   =					text







	def    _lowerCamelCase				(					self		:List[str]						)		-> int:
								if self.new_user_input:
															self.past_user_inputs.append(self.new_user_input						)
								__UpperCamelCase	:   Dict			   =					None







	def    _lowerCamelCase				(					self		:Optional[int]     ,   a		:str						)		-> Optional[int]:
								self.generated_responses.append(a						)







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




@add_end_docstrings(
    __lowercase     ,						R'\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    '     ,						)
class  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	def __init__(					self		:Tuple     ,   *a		:Tuple     ,   **a		:List[str]						)		-> Tuple:
								super().__init__(*a     ,   **a						)
								if self.tokenizer.pad_token_id is None:
															__UpperCamelCase	:   int			   =					self.tokenizer.eos_token







	def    _lowerCamelCase				(					self		:Optional[int]     ,   a		:List[Any]=None     ,   a		:str=None     ,   a		:int=None     ,   **a		:str						)		-> List[str]:
								__UpperCamelCase	:   List[str]			   =					{}
								__UpperCamelCase	:   List[str]			   =					{}
								__UpperCamelCase	:   str			   =					{}

								if min_length_for_response is not None:
															__UpperCamelCase	:   Optional[Any]			   =					min_length_for_response
								if minimum_tokens is not None:
															__UpperCamelCase	:   List[str]			   =					minimum_tokens

								if "max_length" in generate_kwargs:
															__UpperCamelCase	:   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:
															__UpperCamelCase	:   List[Any]			   =					clean_up_tokenization_spaces

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







	def __call__(					self		:Dict     ,   a		:Union[Conversation, List[Conversation]]     ,   a		:List[Any]=0     ,   **a		:Any						)		-> Union[str, Any]:
								__UpperCamelCase	:   Optional[int]			   =					super().__call__(a     ,   num_workers=a     ,   **a						)
								if isinstance(a     ,   a						) and len(a						) == 1:
															return outputs[0]
								return outputs







	def    _lowerCamelCase				(					self		:Tuple     ,   a		:Conversation     ,   a		:Dict=3_2						)		-> Dict[str, Any]:
								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	:   str			   =					self.tokenizer._build_conversation_input_ids(a						)
								else:
															# If the tokenizer cannot handle conversations, we default to only the old version
															__UpperCamelCase	:   Optional[Any]			   =					self._legacy_parse_and_tokenize(a						)

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







	def    _lowerCamelCase				(					self		:Any     ,   a		:List[Any]     ,   a		:Optional[Any]=1_0     ,   **a		:Tuple						)		-> List[str]:
								__UpperCamelCase	:   Union[str, Any]			   =					generate_kwargs.get("max_length"     ,   self.model.config.max_length						)

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







	def    _lowerCamelCase				(					self		:List[Any]     ,   a		:str     ,   a		:Optional[int]=True						)		-> Union[str, Any]:
								__UpperCamelCase	:   List[str]			   =					model_outputs["output_ids"]
								__UpperCamelCase	:   Any			   =					self.tokenizer.decode(
								    output_ids[0]     ,   skip_special_tokens=a     ,   clean_up_tokenization_spaces=a     ,   )
								__UpperCamelCase	:   int			   =					model_outputs["conversation"]
								conversation.mark_processed()
								conversation.append_response(a						)
								return conversation







	def    _lowerCamelCase				(					self		:str     ,   a		:Conversation						)		-> Dict:
								__UpperCamelCase	:   int			   =					self.tokenizer.eos_token_id
								__UpperCamelCase	:   Any			   =					[]
								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	:   Union[str, Any]			   =					input_ids[-self.tokenizer.model_max_length :]
								return input_ids