


from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
	from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor





class       A    (   A_ ):


							def 			_A       (self					):
									__lowercase=			self.config_class(**self.inputs_dict					)
									self.parent.assertTrue(hasattr(lowerCAmelCase      ,				'embed_dim'					)					)
									self.parent.assertTrue(hasattr(lowerCAmelCase      ,				'num_heads'					)					)





class       A    :


							def __init__(self      ,				lowerCAmelCase      ,				lowerCAmelCase=1_3      ,				lowerCAmelCase=6_4      ,				lowerCAmelCase=3      ,				lowerCAmelCase=[1_6, 4_8, 9_6]      ,				lowerCAmelCase=[1, 3, 6]      ,				lowerCAmelCase=[1, 2, 1_0]      ,				lowerCAmelCase=[7, 3, 3]      ,				lowerCAmelCase=[4, 2, 2]      ,				lowerCAmelCase=[2, 1, 1]      ,				lowerCAmelCase=[2, 2, 2]      ,				lowerCAmelCase=[False, False, True]      ,				lowerCAmelCase=[0.0, 0.0, 0.0]      ,				lowerCAmelCase=0.02      ,				lowerCAmelCase=1E-12      ,				lowerCAmelCase=True      ,				lowerCAmelCase=True      ,				lowerCAmelCase=2      ,				):
									__lowercase=			parent
									__lowercase=			batch_size
									__lowercase=			image_size
									__lowercase=			patch_sizes
									__lowercase=			patch_stride
									__lowercase=			patch_padding
									__lowercase=			is_training
									__lowercase=			use_labels
									__lowercase=			num_labels
									__lowercase=			num_channels
									__lowercase=			embed_dim
									__lowercase=			num_heads
									__lowercase=			stride_kv
									__lowercase=			depth
									__lowercase=			cls_token
									__lowercase=			attention_drop_rate
									__lowercase=			initializer_range
									__lowercase=			layer_norm_eps


							def 			_A       (self					):
									__lowercase=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

									__lowercase=			None
									if self.use_labels:
											# create a random int32 tensor of given shape
											__lowercase=			ids_tensor([self.batch_size]      ,				self.num_labels					)

									__lowercase=			self.get_config()
									return config, pixel_values, labels


							def 			_A       (self					):
									return CvtConfig(
									    image_size=self.image_size      ,				num_labels=self.num_labels      ,				num_channels=self.num_channels      ,				embed_dim=self.embed_dim      ,				num_heads=self.num_heads      ,				patch_sizes=self.patch_sizes      ,				patch_padding=self.patch_padding      ,				patch_stride=self.patch_stride      ,				stride_kv=self.stride_kv      ,				depth=self.depth      ,				cls_token=self.cls_token      ,				attention_drop_rate=self.attention_drop_rate      ,				initializer_range=self.initializer_range      ,				)


							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase      ,				lowerCAmelCase					):
									__lowercase=			TFCvtModel(config=lowerCAmelCase					)
									__lowercase=			model(lowerCAmelCase      ,				training=lowerCAmelCase					)
									__lowercase=			(self.image_size, self.image_size)
									__lowercase,							__lowercase=			image_size[0], image_size[1]
									for i in range(len(self.depth					)					):
											__lowercase=			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1					)
											__lowercase=			floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1					)
									self.parent.assertEqual(result.last_hidden_state.shape      ,				(self.batch_size, self.embed_dim[-1], height, width)					)


							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase      ,				lowerCAmelCase					):
									__lowercase=			self.num_labels
									__lowercase=			TFCvtForImageClassification(lowerCAmelCase					)
									__lowercase=			model(lowerCAmelCase      ,				labels=lowerCAmelCase      ,				training=lowerCAmelCase					)
									self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.num_labels)					)







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





@require_tf
class       A    (   A_					,				A_					,				unittest.TestCase ):
							UpperCamelCase_   :							Optional[int]       =(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
							UpperCamelCase_   :							Dict       =(
							    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
							    if is_tf_available()
							    else {}
							)
							UpperCamelCase_   :							Union[str, Any]       =False
							UpperCamelCase_   :							Optional[int]       =False
							UpperCamelCase_   :							Union[str, Any]       =False
							UpperCamelCase_   :							Optional[int]       =False
							UpperCamelCase_   :							str       =False


							def 			_A       (self					):
									__lowercase=			TFCvtModelTester(self					)
									__lowercase=			TFCvtConfigTester(self      ,				config_class=lowerCAmelCase      ,				has_text_modality=lowerCAmelCase      ,				hidden_size=3_7					)


							def 			_A       (self					):
									self.config_tester.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()


							@unittest.skip(reason='Cvt does not output attentions'					)
							def 			_A       (self					):
									pass


							@unittest.skip(reason='Cvt does not use inputs_embeds'					)
							def 			_A       (self					):
									pass


							@unittest.skip(reason='Cvt does not support input and output embeddings'					)
							def 			_A       (self					):
									pass


							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices('GPU'					)					) == 0      ,				reason='TF does not support backprop for grouped convolutions on CPU.'      ,				)
							def 			_A       (self					):
									super().test_dataset_conversion()


							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices('GPU'					)					) == 0      ,				reason='TF does not support backprop for grouped convolutions on CPU.'      ,				)
							@slow
							def 			_A       (self					):
									super().test_keras_fit()


							@unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'					)
							def 			_A       (self					):
									__lowercase=			tf.keras.mixed_precision.Policy('mixed_float16'					)
									tf.keras.mixed_precision.set_global_policy(lowerCAmelCase					)
									super().test_keras_fit()
									tf.keras.mixed_precision.set_global_policy('float32'					)


							def 			_A       (self					):
									__lowercase,							__lowercase=			self.model_tester.prepare_config_and_inputs_for_common()

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

											__lowercase=			['pixel_values']
											self.assertListEqual(arg_names[:1]      ,				lowerCAmelCase					)


							def 			_A       (self					):
									def check_hidden_states_output(lowerCAmelCase      ,				lowerCAmelCase      ,				lowerCAmelCase					):
											__lowercase=			model_class(lowerCAmelCase					)

											__lowercase=			model(**self._prepare_for_class(lowerCAmelCase      ,				lowerCAmelCase					)					)
											__lowercase=			outputs.hidden_states

											__lowercase=			len(self.model_tester.depth					)
											self.assertEqual(len(lowerCAmelCase					)      ,				lowerCAmelCase					)

											# verify the first hidden states (first block)
											self.assertListEqual(
											    list(hidden_states[0].shape[-3:]					)      ,				[
											        self.model_tester.embed_dim[0],
											        self.model_tester.image_size // 4,
											        self.model_tester.image_size // 4,
											    ]      ,				)

									__lowercase,							__lowercase=			self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											__lowercase=			True
											check_hidden_states_output(lowerCAmelCase      ,				lowerCAmelCase      ,				lowerCAmelCase					)

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

											check_hidden_states_output(lowerCAmelCase      ,				lowerCAmelCase      ,				lowerCAmelCase					)


							def 			_A       (self					):
									__lowercase=			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase					)


							def 			_A       (self					):
									__lowercase=			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase					)







							@slow
							def 			_A       (self					):
									for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowercase=			TFCvtModel.from_pretrained(lowerCAmelCase					)
											self.assertIsNotNone(lowerCAmelCase					)







def        _lowerCamelCase(	)						->	Any:

		'''simple docstring'''







		__lowercase=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
		return image





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


							@cached_property
							def 			_A       (self					):
									return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)







							@slow
							def 			_A       (self					):
									__lowercase=			TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

									__lowercase=			self.default_image_processor
									__lowercase=			prepare_img()
									__lowercase=			image_processor(images=lowerCAmelCase      ,				return_tensors='tf'					)

									# forward pass
									__lowercase=			model(**lowerCAmelCase					)

									# verify the logits
									__lowercase=			tf.TensorShape((1, 1_0_0_0)					)
									self.assertEqual(outputs.logits.shape      ,				lowerCAmelCase					)

									__lowercase=			tf.constant([0.92_85, 0.90_15, -0.31_50]					)
									self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,				lowerCAmelCase      ,				atol=1E-4					)					)










import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf





class       A    (   enum.Enum ):
							UpperCamelCase_   :							Optional[int]       =0
							UpperCamelCase_   :							Tuple       =1
							UpperCamelCase_   :							Optional[int]       =2





@add_end_docstrings(A_ )
class       A    (   A_ ):
							UpperCamelCase_   :							Union[str, Any]       ='''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''


							def __init__(self      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
									super().__init__(*lowerCAmelCase      ,				**lowerCAmelCase					)
									self.check_model_type(
									    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING					)
									if "prefix" not in self._preprocess_params:
											# This is very specific. The logic is quite complex and needs to be done
											# as a "default".
											# It also defines both some preprocess_kwargs and generate_kwargs
											# which is why we cannot put them in their respective methods.
											__lowercase=			None
											if self.model.config.prefix is not None:
													__lowercase=			self.model.config.prefix
											if prefix is None and self.model.__class__.__name__ in [
											    "XLNetLMHeadModel",
											    "TransfoXLLMHeadModel",
											    "TFXLNetLMHeadModel",
											    "TFTransfoXLLMHeadModel",
											]:
													# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
													__lowercase=			self.XL_PREFIX
											if prefix is not None:
													# Recalculate some generate_kwargs linked to prefix.
													__lowercase,							__lowercase,							__lowercase=			self._sanitize_parameters(prefix=lowerCAmelCase      ,				**self._forward_params					)
													__lowercase=			{**self._preprocess_params, **preprocess_params}
													__lowercase=			{**self._forward_params, **forward_params}


							def 			_A       (self      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				**lowerCAmelCase      ,				):
									__lowercase=			{}
									if prefix is not None:
											__lowercase=			prefix
									if prefix:
											__lowercase=			self.tokenizer(
											    lowerCAmelCase      ,				padding=lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase      ,				return_tensors=self.framework					)
											__lowercase=			prefix_inputs['input_ids'].shape[-1]

									if handle_long_generation is not None:
											if handle_long_generation not in {"hole"}:
													raise ValueError(
													    f'{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'
													    ' [None, \'hole\']'					)
											__lowercase=			handle_long_generation

									preprocess_params.update(lowerCAmelCase					)
									__lowercase=			generate_kwargs

									__lowercase=			{}
									if return_full_text is not None and return_type is None:
											if return_text is not None:
													raise ValueError('`return_text` is mutually exclusive with `return_full_text`'					)
											if return_tensors is not None:
													raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`'					)
											__lowercase=			ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
									if return_tensors is not None and return_type is None:
											if return_text is not None:
													raise ValueError('`return_text` is mutually exclusive with `return_tensors`'					)
											__lowercase=			ReturnType.TENSORS
									if return_type is not None:
											__lowercase=			return_type
									if clean_up_tokenization_spaces is not None:
											__lowercase=			clean_up_tokenization_spaces

									if stop_sequence is not None:
											__lowercase=			self.tokenizer.encode(lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase					)
											if len(lowerCAmelCase					) > 1:
													warnings.warn(
													    'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
													    ' the stop sequence will be used as the stop sequence string in the interim.'					)
											__lowercase=			stop_sequence_ids[0]

									return preprocess_params, forward_params, postprocess_params


							def 			_A       (self      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
									# Parse arguments
									if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
											kwargs.update({'add_space_before_punct_symbol': True}					)

									return super()._parse_and_tokenize(*lowerCAmelCase      ,				**lowerCAmelCase					)


							def __call__(self      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									return super().__call__(lowerCAmelCase      ,				**lowerCAmelCase					)


							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase=""      ,				lowerCAmelCase=None      ,				**lowerCAmelCase					):
									__lowercase=			self.tokenizer(
									    prefix + prompt_text      ,				padding=lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase      ,				return_tensors=self.framework					)
									__lowercase=			prompt_text

									if handle_long_generation == "hole":
											__lowercase=			inputs['input_ids'].shape[-1]
											if "max_new_tokens" in generate_kwargs:
													__lowercase=			generate_kwargs['max_new_tokens']
											else:
													__lowercase=			generate_kwargs.get('max_length'      ,				self.model.config.max_length					) - cur_len
													if new_tokens < 0:
															raise ValueError('We cannot infer how many new tokens are expected'					)
											if cur_len + new_tokens > self.tokenizer.model_max_length:
													__lowercase=			self.tokenizer.model_max_length - new_tokens
													if keep_length <= 0:
															raise ValueError(
															    'We cannot use `hole` to handle this generation the number of desired tokens exceeds the'
															    ' models max length'					)

													__lowercase=			inputs['input_ids'][:, -keep_length:]
													if "attention_mask" in inputs:
															__lowercase=			inputs['attention_mask'][:, -keep_length:]

									return inputs


							def 			_A       (self      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									__lowercase=			model_inputs['input_ids']
									__lowercase=			model_inputs.get('attention_mask'      ,				lowerCAmelCase					)
									# Allow empty prompts
									if input_ids.shape[1] == 0:
											__lowercase=			None
											__lowercase=			None
											__lowercase=			1
									else:
											__lowercase=			input_ids.shape[0]
									__lowercase=			model_inputs.pop('prompt_text'					)

									# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
									# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
									__lowercase=			generate_kwargs.pop('prefix_length'      ,				0					)
									if prefix_length > 0:
											__lowercase=			'max_new_tokens' in generate_kwargs or (
											    'generation_config' in generate_kwargs
											    and generate_kwargs['generation_config'].max_new_tokens is not None
											)
											if not has_max_new_tokens:
													__lowercase=			generate_kwargs.get('max_length'					) or self.model.config.max_length
													generate_kwargs["max_length"] += prefix_length
											__lowercase=			'min_new_tokens' in generate_kwargs or (
											    'generation_config' in generate_kwargs
											    and generate_kwargs['generation_config'].min_new_tokens is not None
											)
											if not has_min_new_tokens and "min_length" in generate_kwargs:
													generate_kwargs["min_length"] += prefix_length

        # BS x SL
									__lowercase=			self.model.generate(input_ids=lowerCAmelCase      ,				attention_mask=lowerCAmelCase      ,				**lowerCAmelCase					)
									__lowercase=			generated_sequence.shape[0]
									if self.framework == "pt":
											__lowercase=			generated_sequence.reshape(lowerCAmelCase      ,				out_b // in_b      ,				*generated_sequence.shape[1:]					)
									elif self.framework == "tf":
											__lowercase=			tf.reshape(lowerCAmelCase      ,				(in_b, out_b // in_b, *generated_sequence.shape[1:])					)
									return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase=ReturnType.FULL_TEXT      ,				lowerCAmelCase=True					):
									__lowercase=			model_outputs['generated_sequence'][0]
									__lowercase=			model_outputs['input_ids']
									__lowercase=			model_outputs['prompt_text']
									__lowercase=			generated_sequence.numpy().tolist()
									__lowercase=			[]
									for sequence in generated_sequence:
											if return_type == ReturnType.TENSORS:
													__lowercase=			{'generated_token_ids': sequence}
											elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
													# Decode text
													__lowercase=			self.tokenizer.decode(
													    lowerCAmelCase      ,				skip_special_tokens=lowerCAmelCase      ,				clean_up_tokenization_spaces=lowerCAmelCase      ,				)

													# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
													if input_ids is None:
															__lowercase=			0
													else:
															__lowercase=			len(
															    self.tokenizer.decode(
															        input_ids[0]      ,				skip_special_tokens=lowerCAmelCase      ,				clean_up_tokenization_spaces=lowerCAmelCase      ,				)					)

													if return_type == ReturnType.FULL_TEXT:
															__lowercase=			prompt_text + text[prompt_length:]
													else:
															__lowercase=			text[prompt_length:]

													__lowercase=			{'generated_text': all_text}
											records.append(lowerCAmelCase					)

									return records






