






'''simple docstring'''







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 						SCREAMING_SNAKE_CASE       (       SCREAMING_SNAKE_CASE_							):






			def       SCREAMING_SNAKE_CASE   (			self   :      Dict       )      ->      Tuple:
							a_		:	Tuple									=   self.config_class(**self.inputs_dict       )
							self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,    '''embed_dim'''       )       )
							self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,    '''num_heads'''       )       )





class 						SCREAMING_SNAKE_CASE       :






			def __init__(			self   :      Optional[int]	,    __SCREAMING_SNAKE_CASE   :      Optional[int]	,    __SCREAMING_SNAKE_CASE   :      List[str]=13	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]=64	,    __SCREAMING_SNAKE_CASE   :      Optional[int]=3	,    __SCREAMING_SNAKE_CASE   :      int=[16, 48, 96]	,    __SCREAMING_SNAKE_CASE   :      Any=[1, 3, 6]	,    __SCREAMING_SNAKE_CASE   :      str=[1, 2, 10]	,    __SCREAMING_SNAKE_CASE   :      Tuple=[7, 3, 3]	,    __SCREAMING_SNAKE_CASE   :      Tuple=[4, 2, 2]	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]=[2, 1, 1]	,    __SCREAMING_SNAKE_CASE   :      List[str]=[2, 2, 2]	,    __SCREAMING_SNAKE_CASE   :      Dict=[False, False, True]	,    __SCREAMING_SNAKE_CASE   :      List[Any]=[0.0, 0.0, 0.0]	,    __SCREAMING_SNAKE_CASE   :      Tuple=0.02	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]=1e-12	,    __SCREAMING_SNAKE_CASE   :      Dict=True	,    __SCREAMING_SNAKE_CASE   :      int=True	,    __SCREAMING_SNAKE_CASE   :      List[str]=2	,    )      ->      Optional[int]:
							a_		:	int									=   parent
							a_		:	str									=   batch_size
							a_		:	Dict									=   image_size
							a_		:	int									=   patch_sizes
							a_		:	Optional[int]									=   patch_stride
							a_		:	str									=   patch_padding
							a_		:	Dict									=   is_training
							a_		:	Any									=   use_labels
							a_		:	int									=   num_labels
							a_		:	List[Any]									=   num_channels
							a_		:	List[str]									=   embed_dim
							a_		:	Optional[int]									=   num_heads
							a_		:	List[str]									=   stride_kv
							a_		:	Union[str, Any]									=   depth
							a_		:	Optional[Any]									=   cls_token
							a_		:	Union[str, Any]									=   attention_drop_rate
							a_		:	Optional[int]									=   initializer_range
							a_		:	Dict									=   layer_norm_eps






			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      Tuple:
							a_		:	Dict									=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

							a_		:	str									=   self.get_config()
							return config, pixel_values, labels






			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      Union[str, Any]:
							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       SCREAMING_SNAKE_CASE   (			self   :      Any	,    __SCREAMING_SNAKE_CASE   :      Dict	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      Any       )      ->      Optional[Any]:
							a_		:	Any									=   TFCvtModel(config=__SCREAMING_SNAKE_CASE       )
							a_		:	Union[str, Any]									=   model(__SCREAMING_SNAKE_CASE	,    training=__SCREAMING_SNAKE_CASE       )
							a_		:	str									=   (self.image_size, self.image_size)
							a_					,      a_		:	Optional[Any]									=   image_size[0], image_size[1]
							for i in range(len(self.depth       )       ):
											a_		:	Tuple									=   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
											a_		:	Optional[int]									=   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       SCREAMING_SNAKE_CASE   (			self   :      Any	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      List[Any]       )      ->      List[Any]:
							a_		:	Tuple									=   self.num_labels
							a_		:	List[Any]									=   TFCvtForImageClassification(__SCREAMING_SNAKE_CASE       )
							a_		:	Dict									=   model(__SCREAMING_SNAKE_CASE	,    labels=__SCREAMING_SNAKE_CASE	,    training=__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)       )







			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      int:
							a_		:	Optional[int]									=   self.prepare_config_and_inputs()
							a_					,      a_					,      a_		:	int									=   config_and_inputs
							a_		:	List[str]									=   {'''pixel_values''': pixel_values}
							return config, inputs_dict





@require_tf
class 						SCREAMING_SNAKE_CASE       (       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, unittest.TestCase							):
			snake_case__	=					(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
			snake_case__	=					(
			    {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
			    if is_tf_available()
			    else {}
			)
			snake_case__	=					False
			snake_case__	=					False
			snake_case__	=					False
			snake_case__	=					False
			snake_case__	=					False






			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      Dict:
							a_		:	str									=   TFCvtModelTester(self       )
							a_		:	Tuple									=   TFCvtConfigTester(self	,    config_class=__SCREAMING_SNAKE_CASE	,    has_text_modality=__SCREAMING_SNAKE_CASE	,    hidden_size=37       )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      List[str]:
							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       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      int:
							pass






			@unittest.skip(reason='''Cvt does not use inputs_embeds'''       )
			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Any:
							pass






			@unittest.skip(reason='''Cvt does not support input and output embeddings'''       )
			def       SCREAMING_SNAKE_CASE   (			self   :      List[Any]       )      ->      Optional[int]:
							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       SCREAMING_SNAKE_CASE   (			self   :      int       )      ->      Optional[Any]:
							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       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      str:
							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       SCREAMING_SNAKE_CASE   (			self   :      int       )      ->      Tuple:
							a_		:	Optional[int]									=   tf.keras.mixed_precision.Policy('''mixed_float16'''       )
							tf.keras.mixed_precision.set_global_policy(__SCREAMING_SNAKE_CASE       )
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy('''float32'''       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      Optional[int]:
							a_					,      a_		:	List[str]									=   self.model_tester.prepare_config_and_inputs_for_common()

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

											a_		:	Tuple									=   ['''pixel_values''']
											self.assertListEqual(arg_names[:1]	,    __SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      str:
							def check_hidden_states_output(__SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Any       ):
											a_		:	Any									=   model_class(__SCREAMING_SNAKE_CASE       )

											a_		:	str									=   model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )       )
											a_		:	Dict									=   outputs.hidden_states

											a_		:	Tuple									=   len(self.model_tester.depth       )
											self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    __SCREAMING_SNAKE_CASE       )

											# 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,
											    ]	,    )

							a_					,      a_		:	List[str]									=   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											a_		:	Dict									=   True
											check_hidden_states_output(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											a_		:	Union[str, Any]									=   True

											check_hidden_states_output(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      List[str]:
							a_		:	List[str]									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      int:
							a_		:	List[str]									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE       )







			@slow
			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[Any]:
							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											a_		:	Union[str, Any]									=   TFCvtModel.from_pretrained(__SCREAMING_SNAKE_CASE       )
											self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )





def 		_UpperCAmelCase (				):
				a_		:	Union[str, Any]									=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
				return image





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






			@cached_property
			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      List[str]:
							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )







			@slow
			def       SCREAMING_SNAKE_CASE   (			self   :      Dict       )      ->      Any:
							a_		:	List[str]									=   TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

							a_		:	Optional[Any]									=   self.default_image_processor
							a_		:	Optional[Any]									=   prepare_img()
							a_		:	List[str]									=   image_processor(images=__SCREAMING_SNAKE_CASE	,    return_tensors='''tf'''       )

							# forward pass
							a_		:	List[str]									=   model(**__SCREAMING_SNAKE_CASE       )

							# verify the logits
							a_		:	List[str]									=   tf.TensorShape((1, 1000)       )
							self.assertEqual(outputs.logits.shape	,    __SCREAMING_SNAKE_CASE       )

							a_		:	Union[str, Any]									=   tf.constant([0.9285, 0.9015, -0.3150]       )
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()	,    __SCREAMING_SNAKE_CASE	,    atol=1e-4       )       )












'''simple docstring'''







from __future__ import annotations





def 		_UpperCAmelCase (				__A				: str    ,		__A				: str   ):
				a_		:	int									=   get_failure_array(__A   )

				# 2) Step through text searching for pattern
				a_					,      a_		:	Any									=   0, 0  # index into text, pattern
				while i < len(__A   ):
								if pattern[j] == text[i]:
												if j == (len(__A   ) - 1):
																return True
												j += 1

								# if this is a prefix in our pattern
								# just go back far enough to continue
								elif j > 0:
												a_		:	Any									=   failure[j - 1]
												continue
								i += 1
				return False





def 		_UpperCAmelCase (				__A				: str   ):
				a_		:	Optional[Any]									=   [0]
				a_		:	Any									=   0
				a_		:	int									=   1
				while j < len(__A   ):
								if pattern[i] == pattern[j]:
												i += 1
								elif i > 0:
												a_		:	List[Any]									=   failure[i - 1]
												continue
								j += 1
								failure.append(__A   )
				return failure


if __name__ == "__main__":
		# Test 1)
		__lowerCAmelCase									=   'abc1abc12'
		__lowerCAmelCase									=   'alskfjaldsabc1abc1abc12k23adsfabcabc'
		__lowerCAmelCase									=   'alskfjaldsk23adsfabcabc'
		assert kmp(pattern, texta) and not kmp(pattern, texta)

		# Test 2)
		__lowerCAmelCase									=   'ABABX'
		__lowerCAmelCase									=   'ABABZABABYABABX'
		assert kmp(pattern, text)

		# Test 3)
		__lowerCAmelCase									=   'AAAB'
		__lowerCAmelCase									=   'ABAAAAAB'
		assert kmp(pattern, text)

		# Test 4)
		__lowerCAmelCase									=   'abcdabcy'
		__lowerCAmelCase									=   'abcxabcdabxabcdabcdabcy'
		assert kmp(pattern, text)

		# Test 5)
		__lowerCAmelCase									=   'aabaabaaa'
		assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]




