



import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
						import jax
						import jax.numpy as jnp

						from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor



class 							__snake_case		(	unittest.TestCase		):




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




							def   UpperCAmelCase__     (			self	:			Tuple):
									lowerCAmelCase_     :	int							   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

									lowerCAmelCase_     :	List[str]							   =					self.get_config()

									return config, pixel_values




							def   UpperCAmelCase__     (			self	:			int):
									return RegNetConfig(
									    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   UpperCAmelCase__     (			self	:			Union[str, Any]							,							A_	:			Tuple							,							A_	:			Union[str, Any]):
									lowerCAmelCase_     :	Union[str, Any]							   =					FlaxRegNetModel(config=A_)
									lowerCAmelCase_     :	Dict							   =					model(A_)

									# Output shape (b, c, h, w)
									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   UpperCAmelCase__     (			self	:			List[Any]							,							A_	:			Optional[Any]							,							A_	:			Any):
									lowerCAmelCase_     :	List[Any]							   =					self.num_labels
									lowerCAmelCase_     :	str							   =					FlaxRegNetForImageClassification(config=A_)
									lowerCAmelCase_     :	List[str]							   =					model(A_)
									self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.num_labels))







							def   UpperCAmelCase__     (			self	:			Optional[int]):
									lowerCAmelCase_     :	List[Any]							   =					self.prepare_config_and_inputs()
									lowerCAmelCase_   ,    lowerCAmelCase_     :	Optional[int]							   =					config_and_inputs
									lowerCAmelCase_     :	str							   =					{'''pixel_values''': pixel_values}
									return config, inputs_dict





@require_flax
class 							__snake_case		(	snake_case_		,unittest.TestCase		):
							_a      =					(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

							_a      =					False
							_a      =					False
							_a      =					False




							def   UpperCAmelCase__     (			self	:			Optional[Any]):
									lowerCAmelCase_     :	Optional[Any]							   =					FlaxRegNetModelTester(self)
									lowerCAmelCase_     :	Optional[int]							   =					ConfigTester(self							,							config_class=A_							,							has_text_modality=A_)




							def   UpperCAmelCase__     (			self	:			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   UpperCAmelCase__     (			self	:			Dict):
									return




							def   UpperCAmelCase__     (			self	:			int):
									lowerCAmelCase_     :	Tuple							   =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*A_)




							def   UpperCAmelCase__     (			self	:			List[str]):
									lowerCAmelCase_     :	int							   =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*A_)




							@unittest.skip(reason='''RegNet does not use inputs_embeds''')
							def   UpperCAmelCase__     (			self	:			Union[str, Any]):
									pass




							@unittest.skip(reason='''RegNet does not support input and output embeddings''')
							def   UpperCAmelCase__     (			self	:			List[str]):
									pass




							def   UpperCAmelCase__     (			self	:			Any):
									lowerCAmelCase_   ,    lowerCAmelCase_     :	int							   =					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowerCAmelCase_     :	int							   =					model_class(A_)
											lowerCAmelCase_     :	int							   =					inspect.signature(model.__call__)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											lowerCAmelCase_     :	Optional[int]							   =					[*signature.parameters.keys()]

											lowerCAmelCase_     :	Optional[int]							   =					['''pixel_values''']
											self.assertListEqual(arg_names[:1]							,							A_)




							def   UpperCAmelCase__     (			self	:			Tuple):






									def check_hidden_states_output(A_	:			Optional[int]							,							A_	:			str							,							A_	:			Union[str, Any]):
											lowerCAmelCase_     :	Tuple							   =					model_class(A_)

											lowerCAmelCase_     :	List[Any]							   =					model(**self._prepare_for_class(A_							,							A_))

											lowerCAmelCase_     :	Union[str, Any]							   =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											lowerCAmelCase_     :	Tuple							   =					self.model_tester.num_stages
											self.assertEqual(len(A_)							,							expected_num_stages + 1)

									lowerCAmelCase_   ,    lowerCAmelCase_     :	Dict							   =					self.model_tester.prepare_config_and_inputs_for_common()

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

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

											check_hidden_states_output(A_							,							A_							,							A_)







							def   UpperCAmelCase__     (			self	:			str):
									lowerCAmelCase_   ,    lowerCAmelCase_     :	int							   =					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__):
													lowerCAmelCase_     :	List[str]							   =					self._prepare_for_class(A_							,							A_)
													lowerCAmelCase_     :	Any							   =					model_class(A_)

													@jax.jit
													def model_jitted(A_	:			List[Any]							,							**A_	:			Any):
															return model(pixel_values=A_							,							**A_)

													with self.subTest('''JIT Enabled'''):
															lowerCAmelCase_     :	Dict							   =					model_jitted(**A_).to_tuple()

													with self.subTest('''JIT Disabled'''):
															with jax.disable_jit():
																	lowerCAmelCase_     :	Any							   =					model_jitted(**A_).to_tuple()

													self.assertEqual(len(A_)							,							len(A_))
													for jitted_output, output in zip(A_							,							A_):
															self.assertEqual(jitted_output.shape							,							output.shape)





def      UpperCamelCase(    ):
		lowerCAmelCase_     :	List[str]							   =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
		return image





@require_flax
class 							__snake_case		(	unittest.TestCase		):




							@cached_property
							def   UpperCAmelCase__     (			self	:			Dict):
									return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''') if is_vision_available() else None







							@slow
							def   UpperCAmelCase__     (			self	:			Optional[Any]):
									lowerCAmelCase_     :	List[str]							   =					FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''')

									lowerCAmelCase_     :	str							   =					self.default_image_processor
									lowerCAmelCase_     :	Optional[Any]							   =					prepare_img()
									lowerCAmelCase_     :	Tuple							   =					image_processor(images=A_							,							return_tensors='''np''')

									lowerCAmelCase_     :	Optional[Any]							   =					model(**A_)

									# verify the logits
									lowerCAmelCase_     :	int							   =					(1, 1_0_0_0)
									self.assertEqual(outputs.logits.shape							,							A_)

									lowerCAmelCase_     :	List[str]							   =					jnp.array([-0.4180, -1.5051, -3.4836])

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







'''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




