



"""simple docstring"""






from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

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


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
		    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
		    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
		    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
		    LayoutLMvaConfig,
		    TFLayoutLMvaForQuestionAnswering,
		    TFLayoutLMvaForSequenceClassification,
		    TFLayoutLMvaForTokenClassification,
		    TFLayoutLMvaModel,
		)

if is_vision_available():
		from PIL import Image

		from transformers import LayoutLMvaImageProcessor

class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





					def __init__(       self							:  Tuple,  lowerCamelCase							:  Any,  lowerCamelCase							:  Union[str, Any]=2,  lowerCamelCase							:  int=3,  lowerCamelCase							:  int=4,  lowerCamelCase							:  List[Any]=2,  lowerCamelCase							:  Dict=7,  lowerCamelCase							:  Dict=True,  lowerCamelCase							:  Union[str, Any]=True,  lowerCamelCase							:  Optional[int]=True,  lowerCamelCase							:  Union[str, Any]=True,  lowerCamelCase							:  Optional[int]=99,  lowerCamelCase							:  List[Any]=36,  lowerCamelCase							:  Union[str, Any]=2,  lowerCamelCase							:  List[str]=4,  lowerCamelCase							:  List[str]=37,  lowerCamelCase							:  List[Any]="gelu",  lowerCamelCase							:  Any=0.1,  lowerCamelCase							:  int=0.1,  lowerCamelCase							:  Tuple=512,  lowerCamelCase							:  int=16,  lowerCamelCase							:  Union[str, Any]=2,  lowerCamelCase							:  Union[str, Any]=0.02,  lowerCamelCase							:  Union[str, Any]=6,  lowerCamelCase							:  Tuple=6,  lowerCamelCase							:  Any=3,  lowerCamelCase							:  Optional[Any]=4,  lowerCamelCase							:  Optional[Any]=None,  lowerCamelCase							:  Tuple=1000,  )->					str:
								lowerCamelCase__		:		List[Any]			=parent
								lowerCamelCase__		:		Any			=batch_size
								lowerCamelCase__		:		Dict			=num_channels
								lowerCamelCase__		:		Optional[Any]			=image_size
								lowerCamelCase__		:		str			=patch_size
								lowerCamelCase__		:		int			=is_training
								lowerCamelCase__		:		Dict			=use_input_mask
								lowerCamelCase__		:		Tuple			=use_token_type_ids
								lowerCamelCase__		:		Dict			=use_labels
								lowerCamelCase__		:		List[str]			=vocab_size
								lowerCamelCase__		:		Optional[Any]			=hidden_size
								lowerCamelCase__		:		Tuple			=num_hidden_layers
								lowerCamelCase__		:		str			=num_attention_heads
								lowerCamelCase__		:		Optional[int]			=intermediate_size
								lowerCamelCase__		:		List[str]			=hidden_act
								lowerCamelCase__		:		str			=hidden_dropout_prob
								lowerCamelCase__		:		int			=attention_probs_dropout_prob
								lowerCamelCase__		:		Optional[Any]			=max_position_embeddings
								lowerCamelCase__		:		Union[str, Any]			=type_vocab_size
								lowerCamelCase__		:		int			=type_sequence_label_size
								lowerCamelCase__		:		Dict			=initializer_range
								lowerCamelCase__		:		str			=coordinate_size
								lowerCamelCase__		:		Tuple			=shape_size
								lowerCamelCase__		:		Optional[int]			=num_labels
								lowerCamelCase__		:		Optional[int]			=num_choices
								lowerCamelCase__		:		List[str]			=scope
								lowerCamelCase__		:		Dict			=range_bbox

								# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
								lowerCamelCase__		:		List[str]			=text_seq_length
								lowerCamelCase__		:		Any			=(image_size // patch_size) ** 2 + 1
								lowerCamelCase__		:		Optional[Any]			=self.text_seq_length + self.image_seq_length



					def 		snake_case       (       self							:  Optional[Any]     )->					int:
								lowerCamelCase__		:		int			=ids_tensor([self.batch_size, self.text_seq_length],  self.vocab_size     )

								lowerCamelCase__		:		List[Any]			=ids_tensor([self.batch_size, self.text_seq_length, 4],  self.range_bbox     )
								lowerCamelCase__		:		str			=bbox.numpy()
								# Ensure that bbox is legal
								for i in range(bbox.shape[0]     ):
											for j in range(bbox.shape[1]     ):
														if bbox[i, j, 3] < bbox[i, j, 1]:
																	lowerCamelCase__		:		Union[str, Any]			=bbox[i, j, 3]
																	lowerCamelCase__		:		Dict			=bbox[i, j, 1]
																	lowerCamelCase__		:		Tuple			=tmp_coordinate
														if bbox[i, j, 2] < bbox[i, j, 0]:
																	lowerCamelCase__		:		str			=bbox[i, j, 2]
																	lowerCamelCase__		:		List[Any]			=bbox[i, j, 0]
																	lowerCamelCase__		:		Tuple			=tmp_coordinate
								lowerCamelCase__		:		List[str]			=tf.constant(lowerCamelCase     )

								lowerCamelCase__		:		str			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

								lowerCamelCase__		:		List[str]			=None
								if self.use_input_mask:
											lowerCamelCase__		:		Union[str, Any]			=random_attention_mask([self.batch_size, self.text_seq_length]     )

								lowerCamelCase__		:		str			=None
								if self.use_token_type_ids:
											lowerCamelCase__		:		Optional[int]			=ids_tensor([self.batch_size, self.text_seq_length],  self.type_vocab_size     )

								lowerCamelCase__		:		List[str]			=None
								lowerCamelCase__		:		int			=None
								if self.use_labels:
											lowerCamelCase__		:		Union[str, Any]			=ids_tensor([self.batch_size],  self.type_sequence_label_size     )
											lowerCamelCase__		:		Optional[int]			=ids_tensor([self.batch_size, self.text_seq_length],  self.num_labels     )

								lowerCamelCase__		:		Dict			=LayoutLMvaConfig(
								    vocab_size=self.vocab_size,  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,  max_position_embeddings=self.max_position_embeddings,  type_vocab_size=self.type_vocab_size,  initializer_range=self.initializer_range,  coordinate_size=self.coordinate_size,  shape_size=self.shape_size,  input_size=self.image_size,  patch_size=self.patch_size,  )

								return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels



					def 		snake_case       (       self							:  int,  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  Any,  lowerCamelCase							:  List[str],  lowerCamelCase							:  Any,  lowerCamelCase							:  Any,  lowerCamelCase							:  Union[str, Any]     )->					Dict:
								lowerCamelCase__		:		str			=TFLayoutLMvaModel(config=lowerCamelCase     )

								# text + image
								lowerCamelCase__		:		Optional[Any]			=model(lowerCamelCase,  pixel_values=lowerCamelCase,  training=lowerCamelCase     )
								lowerCamelCase__		:		List[str]			=model(
								    lowerCamelCase,  bbox=lowerCamelCase,  pixel_values=lowerCamelCase,  attention_mask=lowerCamelCase,  token_type_ids=lowerCamelCase,  training=lowerCamelCase,  )
								lowerCamelCase__		:		List[Any]			=model(lowerCamelCase,  bbox=lowerCamelCase,  pixel_values=lowerCamelCase,  training=lowerCamelCase     )

								self.parent.assertEqual(result.last_hidden_state.shape,  (self.batch_size, self.seq_length, self.hidden_size)     )

								# text only
								lowerCamelCase__		:		Any			=model(lowerCamelCase,  training=lowerCamelCase     )
								self.parent.assertEqual(
								    result.last_hidden_state.shape,  (self.batch_size, self.text_seq_length, self.hidden_size)     )

								# image only
								lowerCamelCase__		:		List[Any]			=model({'''pixel_values''': pixel_values},  training=lowerCamelCase     )
								self.parent.assertEqual(
								    result.last_hidden_state.shape,  (self.batch_size, self.image_seq_length, self.hidden_size)     )



					def 		snake_case       (       self							:  Optional[int],  lowerCamelCase							:  Any,  lowerCamelCase							:  List[str],  lowerCamelCase							:  Any,  lowerCamelCase							:  Dict,  lowerCamelCase							:  int,  lowerCamelCase							:  Any,  lowerCamelCase							:  Any     )->					List[Any]:
								lowerCamelCase__		:		Dict			=self.num_labels
								lowerCamelCase__		:		Tuple			=TFLayoutLMvaForSequenceClassification(config=lowerCamelCase     )
								lowerCamelCase__		:		Any			=model(
								    lowerCamelCase,  bbox=lowerCamelCase,  pixel_values=lowerCamelCase,  attention_mask=lowerCamelCase,  token_type_ids=lowerCamelCase,  labels=lowerCamelCase,  training=lowerCamelCase,  )
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.num_labels)     )



					def 		snake_case       (       self							:  int,  lowerCamelCase							:  Tuple,  lowerCamelCase							:  Any,  lowerCamelCase							:  Any,  lowerCamelCase							:  str,  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  int,  lowerCamelCase							:  Optional[int]     )->					List[Any]:
								lowerCamelCase__		:		str			=self.num_labels
								lowerCamelCase__		:		str			=TFLayoutLMvaForTokenClassification(config=lowerCamelCase     )
								lowerCamelCase__		:		Any			=model(
								    lowerCamelCase,  bbox=lowerCamelCase,  pixel_values=lowerCamelCase,  attention_mask=lowerCamelCase,  token_type_ids=lowerCamelCase,  labels=lowerCamelCase,  training=lowerCamelCase,  )
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.text_seq_length, self.num_labels)     )



					def 		snake_case       (       self							:  Union[str, Any],  lowerCamelCase							:  int,  lowerCamelCase							:  Dict,  lowerCamelCase							:  Any,  lowerCamelCase							:  List[str],  lowerCamelCase							:  List[str],  lowerCamelCase							:  int,  lowerCamelCase							:  Tuple     )->					Optional[Any]:
								lowerCamelCase__		:		Any			=2
								lowerCamelCase__		:		Optional[Any]			=TFLayoutLMvaForQuestionAnswering(config=lowerCamelCase     )
								lowerCamelCase__		:		Union[str, Any]			=model(
								    lowerCamelCase,  bbox=lowerCamelCase,  pixel_values=lowerCamelCase,  attention_mask=lowerCamelCase,  token_type_ids=lowerCamelCase,  start_positions=lowerCamelCase,  end_positions=lowerCamelCase,  training=lowerCamelCase,  )
								self.parent.assertEqual(result.start_logits.shape,  (self.batch_size, self.seq_length)     )
								self.parent.assertEqual(result.end_logits.shape,  (self.batch_size, self.seq_length)     )




					def 		snake_case       (       self							:  List[Any]     )->					Optional[Any]:
								lowerCamelCase__		:		Optional[Any]			=self.prepare_config_and_inputs()
								((lowerCamelCase__)	,   (lowerCamelCase__)	,   (lowerCamelCase__)	,   (lowerCamelCase__)	,   (lowerCamelCase__)	,   (lowerCamelCase__)	,   (lowerCamelCase__)	,   (lowerCamelCase__))		:		Any			=config_and_inputs
								lowerCamelCase__		:		int			={
								    '''input_ids''': input_ids,
								    '''bbox''': bbox,
								    '''pixel_values''': pixel_values,
								    '''token_type_ids''': token_type_ids,
								    '''attention_mask''': input_mask,
								}
								return config, inputs_dict





@require_tf
class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_		,   lowerCAmelCase_		,   unittest.TestCase   ):


					'''simple docstring'''





					_a   			=							(
					    (
					        TFLayoutLMvaModel,
					        TFLayoutLMvaForQuestionAnswering,
					        TFLayoutLMvaForSequenceClassification,
					        TFLayoutLMvaForTokenClassification,
					    )
					    if is_tf_available()
					    else ()
					)
					_a   			=							(
					    {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
					    if is_tf_available()
					    else {}
					)

					_a   			=							False
					_a   			=							False
					_a   			=							False



					def 		snake_case       (       self							:  Dict,  lowerCamelCase							:  int,  lowerCamelCase							:  List[Any],  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  int     )->					str:
								return True



					def 		snake_case       (       self							:  List[str],  lowerCamelCase							:  Tuple,  lowerCamelCase							:  Tuple,  lowerCamelCase							:  Optional[Any]=False     )->					dict:
								lowerCamelCase__		:		List[str]			=copy.deepcopy(lowerCamelCase     )

								if model_class in get_values(lowerCamelCase     ):
											lowerCamelCase__		:		Dict			={
											    k: tf.tile(tf.expand_dims(lowerCamelCase,  1     ),  (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)     )
											    if isinstance(lowerCamelCase,  tf.Tensor     ) and v.ndim > 0
											    else v
											    for k, v in inputs_dict.items()
											}

								if return_labels:
											if model_class in get_values(lowerCamelCase     ):
														lowerCamelCase__		:		Any			=tf.ones(self.model_tester.batch_size,  dtype=tf.intaa     )
											elif model_class in get_values(lowerCamelCase     ):
														lowerCamelCase__		:		Optional[Any]			=tf.zeros(self.model_tester.batch_size,  dtype=tf.intaa     )
														lowerCamelCase__		:		Any			=tf.zeros(self.model_tester.batch_size,  dtype=tf.intaa     )
											elif model_class in get_values(lowerCamelCase     ):
														lowerCamelCase__		:		int			=tf.zeros(self.model_tester.batch_size,  dtype=tf.intaa     )
											elif model_class in get_values(lowerCamelCase     ):
														lowerCamelCase__		:		List[str]			=tf.zeros(
														    (self.model_tester.batch_size, self.model_tester.text_seq_length),  dtype=tf.intaa     )

								return inputs_dict



					def 		snake_case       (       self							:  str     )->					Dict:
								lowerCamelCase__		:		List[Any]			=TFLayoutLMvaModelTester(self     )
								lowerCamelCase__		:		List[str]			=ConfigTester(self,  config_class=lowerCamelCase,  hidden_size=37     )



					def 		snake_case       (       self							:  Optional[int]     )->					Optional[Any]:
								self.config_tester.run_common_tests()



					def 		snake_case       (       self							:  Any     )->					Optional[int]:
								lowerCamelCase__	,   lowerCamelCase__		:		Any			=self.model_tester.prepare_config_and_inputs_for_common()
								for model_class in self.all_model_classes:
											lowerCamelCase__		:		Optional[int]			=model_class(lowerCamelCase     )
											if getattr(lowerCamelCase,  '''hf_compute_loss''',  lowerCamelCase     ):
														# The number of elements in the loss should be the same as the number of elements in the label
														lowerCamelCase__		:		Dict			=self._prepare_for_class(inputs_dict.copy(),  lowerCamelCase,  return_labels=lowerCamelCase     )
														lowerCamelCase__		:		List[str]			=prepared_for_class[
														    sorted(prepared_for_class.keys() - inputs_dict.keys(),  reverse=lowerCamelCase     )[0]
														]
														lowerCamelCase__		:		int			=added_label.shape.as_list()[:1]

														# Test that model correctly compute the loss with kwargs
														lowerCamelCase__		:		Union[str, Any]			=self._prepare_for_class(inputs_dict.copy(),  lowerCamelCase,  return_labels=lowerCamelCase     )
														lowerCamelCase__		:		List[str]			=prepared_for_class.pop('''input_ids'''     )

														lowerCamelCase__		:		Optional[Any]			=model(lowerCamelCase,  **lowerCamelCase     )[0]
														self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]     )

														# Test that model correctly compute the loss when we mask some positions
														lowerCamelCase__		:		Optional[Any]			=self._prepare_for_class(inputs_dict.copy(),  lowerCamelCase,  return_labels=lowerCamelCase     )
														lowerCamelCase__		:		Optional[int]			=prepared_for_class.pop('''input_ids'''     )
														if "labels" in prepared_for_class:
																	lowerCamelCase__		:		Tuple			=prepared_for_class['''labels'''].numpy()
																	if len(labels.shape     ) > 1 and labels.shape[1] != 1:
																				lowerCamelCase__		:		Union[str, Any]			=-100
																				lowerCamelCase__		:		Any			=tf.convert_to_tensor(lowerCamelCase     )
																				lowerCamelCase__		:		Any			=model(lowerCamelCase,  **lowerCamelCase     )[0]
																				self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]     )
																				self.assertTrue(not np.any(np.isnan(loss.numpy()     )     )     )

                # Test that model correctly compute the loss with a dict
														lowerCamelCase__		:		Union[str, Any]			=self._prepare_for_class(inputs_dict.copy(),  lowerCamelCase,  return_labels=lowerCamelCase     )
														lowerCamelCase__		:		Optional[int]			=model(lowerCamelCase     )[0]
														self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]     )

														# Test that model correctly compute the loss with a tuple
														lowerCamelCase__		:		Optional[int]			=self._prepare_for_class(inputs_dict.copy(),  lowerCamelCase,  return_labels=lowerCamelCase     )

														# Get keys that were added with the _prepare_for_class function
														lowerCamelCase__		:		Optional[Any]			=prepared_for_class.keys() - inputs_dict.keys()
														lowerCamelCase__		:		List[str]			=inspect.signature(model.call     ).parameters
														lowerCamelCase__		:		Union[str, Any]			=list(signature.keys()     )

														# Create a dictionary holding the location of the tensors in the tuple
														lowerCamelCase__		:		Optional[Any]			={0: '''input_ids'''}
														for label_key in label_keys:
																	lowerCamelCase__		:		str			=signature_names.index(lowerCamelCase     )
																	lowerCamelCase__		:		Dict			=label_key
														lowerCamelCase__		:		Tuple			=sorted(tuple_index_mapping.items()     )
														# Initialize a list with their default values, update the values and convert to a tuple
														lowerCamelCase__		:		Optional[Any]			=[]

														for name in signature_names:
																	if name != "kwargs":
																				list_input.append(signature[name].default     )

														for index, value in sorted_tuple_index_mapping:
																	lowerCamelCase__		:		Optional[Any]			=prepared_for_class[value]

														lowerCamelCase__		:		Tuple			=tuple(lowerCamelCase     )

														# Send to model
														lowerCamelCase__		:		Union[str, Any]			=model(tuple_input[:-1]     )[0]

														self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]     )



					def 		snake_case       (       self							:  List[Any]     )->					Optional[int]:
								(
								    (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   
								)		:		Dict			=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )



					def 		snake_case       (       self							:  str     )->					Any:
								(
								    (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   
								)		:		Any			=self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
											lowerCamelCase__		:		Optional[Any]			=type
											self.model_tester.create_and_check_model(lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )



					def 		snake_case       (       self							:  Tuple     )->					str:
								(
								    (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   
								)		:		Dict			=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(
								    lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )



					def 		snake_case       (       self							:  Optional[int]     )->					Optional[Any]:
								(
								    (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   
								)		:		int			=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(
								    lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )



					def 		snake_case       (       self							:  Dict     )->					Any:
								(
								    (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   (
								    lowerCamelCase__
								)	,   
								)		:		Optional[Any]			=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(
								    lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )




					@slow
					def 		snake_case       (       self							:  Union[str, Any]     )->					List[str]:
								for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase__		:		List[Any]			=TFLayoutLMvaModel.from_pretrained(lowerCamelCase     )
											self.assertIsNotNone(lowerCamelCase     )






def      snake_case__   (		):
			"""simple docstring"""
			lowerCamelCase__		:		List[str]			=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
			return image

@require_tf
class        __SCREAMING_SNAKE_CASE	(      unittest.TestCase   ):


					'''simple docstring'''





					@cached_property
					def 		snake_case       (       self							:  List[str]     )->					Tuple:
								return LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase     ) if is_vision_available() else None




					@slow
					def 		snake_case       (       self							:  int     )->					str:
								lowerCamelCase__		:		Optional[Any]			=TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''     )

								lowerCamelCase__		:		Optional[int]			=self.default_image_processor
								lowerCamelCase__		:		Dict			=prepare_img()
								lowerCamelCase__		:		List[Any]			=image_processor(images=lowerCamelCase,  return_tensors='''tf'''     ).pixel_values

								lowerCamelCase__		:		str			=tf.constant([[1, 2]]     )
								lowerCamelCase__		:		Dict			=tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]     ),  axis=0     )

								# forward pass
								lowerCamelCase__		:		int			=model(input_ids=lowerCamelCase,  bbox=lowerCamelCase,  pixel_values=lowerCamelCase,  training=lowerCamelCase     )

								# verify the logits
								lowerCamelCase__		:		str			=(1, 199, 768)
								self.assertEqual(outputs.last_hidden_state.shape,  lowerCamelCase     )

								lowerCamelCase__		:		str			=tf.constant(
								    [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]]     )

								self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3],  lowerCamelCase,  atol=1E-4     )     )









"""simple docstring"""






import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
		import jax.numpy as jnp

class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def __get__(       self							:  Tuple,  lowerCamelCase							:  List[str],  lowerCamelCase							:  Optional[int]=None     )->					List[str]:
								# See docs.python.org/3/howto/descriptor.html#properties
								if obj is None:
											return self
								if self.fget is None:
											raise AttributeError('''unreadable attribute'''     )
								lowerCamelCase__		:		List[str]			='''__cached_''' + self.fget.__name__
								lowerCamelCase__		:		List[Any]			=getattr(lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )
								if cached is None:
											lowerCamelCase__		:		Optional[int]			=self.fget(lowerCamelCase     )
											setattr(lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )
								return cached






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Optional[Any]			=val.lower()
			if val in {"y", "yes", "t", "true", "on", "1"}:
						return 1
			if val in {"n", "no", "f", "false", "off", "0"}:
						return 0
			raise ValueError(f'''invalid truth value {val!r}'''	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			if is_torch_fx_proxy(__lowerCamelCase	):
						return True
			if is_torch_available():
						import torch

						if isinstance(__lowerCamelCase							,		torch.Tensor	):
									return True
			if is_tf_available():
						import tensorflow as tf

						if isinstance(__lowerCamelCase							,		tf.Tensor	):
									return True

			if is_flax_available():
						import jax.numpy as jnp
						from jax.core import Tracer

						if isinstance(__lowerCamelCase							,		(jnp.ndarray, Tracer)	):
									return True

			return isinstance(__lowerCamelCase							,		np.ndarray	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			return isinstance(__lowerCamelCase							,		np.ndarray	)






def      snake_case__   (		__lowerCamelCase				:    Union[str, Any]	):
			"""simple docstring"""
			return _is_numpy(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Any	):
			"""simple docstring"""
			import torch

			return isinstance(__lowerCamelCase							,		torch.Tensor	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			return False if not is_torch_available() else _is_torch(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			import torch

			return isinstance(__lowerCamelCase							,		torch.device	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			return False if not is_torch_available() else _is_torch_device(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Tuple	):
			"""simple docstring"""
			import torch

			if isinstance(__lowerCamelCase							,		__lowerCamelCase	):
						if hasattr(__lowerCamelCase							,		__lowerCamelCase	):
									lowerCamelCase__		:		Tuple			=getattr(__lowerCamelCase							,		__lowerCamelCase	)
						else:
									return False
			return isinstance(__lowerCamelCase							,		torch.dtype	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			return False if not is_torch_available() else _is_torch_dtype(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			import tensorflow as tf

			return isinstance(__lowerCamelCase							,		tf.Tensor	)






def      snake_case__   (		__lowerCamelCase				:    int	):
			"""simple docstring"""
			return False if not is_tf_available() else _is_tensorflow(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			import tensorflow as tf

			# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
			if hasattr(__lowerCamelCase							,		'''is_symbolic_tensor'''	):
						return tf.is_symbolic_tensor(__lowerCamelCase	)
			return type(__lowerCamelCase	) == tf.Tensor






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			return False if not is_tf_available() else _is_tf_symbolic_tensor(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			import jax.numpy as jnp  # noqa: F811

			return isinstance(__lowerCamelCase							,		jnp.ndarray	)






def      snake_case__   (		__lowerCamelCase				:    Tuple	):
			"""simple docstring"""
			return False if not is_flax_available() else _is_jax(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			if isinstance(__lowerCamelCase							,		(dict, UserDict)	):
						return {k: to_py_obj(__lowerCamelCase	) for k, v in obj.items()}
			elif isinstance(__lowerCamelCase							,		(list, tuple)	):
						return [to_py_obj(__lowerCamelCase	) for o in obj]
			elif is_tf_tensor(__lowerCamelCase	):
						return obj.numpy().tolist()
			elif is_torch_tensor(__lowerCamelCase	):
						return obj.detach().cpu().tolist()
			elif is_jax_tensor(__lowerCamelCase	):
						return np.asarray(__lowerCamelCase	).tolist()
			elif isinstance(__lowerCamelCase							,		(np.ndarray, np.number)	):  # tolist also works on 0d np arrays
						return obj.tolist()
			else:
						return obj






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			if isinstance(__lowerCamelCase							,		(dict, UserDict)	):
						return {k: to_numpy(__lowerCamelCase	) for k, v in obj.items()}
			elif isinstance(__lowerCamelCase							,		(list, tuple)	):
						return np.array(__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						return obj.numpy()
			elif is_torch_tensor(__lowerCamelCase	):
						return obj.detach().cpu().numpy()
			elif is_jax_tensor(__lowerCamelCase	):
						return np.asarray(__lowerCamelCase	)
			else:
						return obj

class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def 		snake_case       (       self							:  int     )->					Optional[int]:
								lowerCamelCase__		:		Union[str, Any]			=fields(self     )

								# Safety and consistency checks
								if not len(lowerCamelCase     ):
											raise ValueError(F'''{self.__class__.__name__} has no fields.'''     )
								if not all(field.default is None for field in class_fields[1:]     ):
											raise ValueError(F'''{self.__class__.__name__} should not have more than one required field.'''     )

								lowerCamelCase__		:		List[Any]			=getattr(self,  class_fields[0].name     )
								lowerCamelCase__		:		Union[str, Any]			=all(getattr(self,  field.name     ) is None for field in class_fields[1:]     )

								if other_fields_are_none and not is_tensor(lowerCamelCase     ):
											if isinstance(lowerCamelCase,  lowerCamelCase     ):
														lowerCamelCase__		:		Optional[int]			=first_field.items()
														lowerCamelCase__		:		Union[str, Any]			=True
											else:
														try:
																	lowerCamelCase__		:		int			=iter(lowerCamelCase     )
																	lowerCamelCase__		:		List[Any]			=True
														except TypeError:
																	lowerCamelCase__		:		List[Any]			=False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
											if first_field_iterator:
														for idx, element in enumerate(lowerCamelCase     ):
																	if (
																	    not isinstance(lowerCamelCase,  (list, tuple)     )
																	    or not len(lowerCamelCase     ) == 2
																	    or not isinstance(element[0],  lowerCamelCase     )
																	):
																				if idx == 0:
																							# If we do not have an iterator of key/values, set it as attribute
																							lowerCamelCase__		:		Optional[int]			=first_field
																				else:
																							# If we have a mixed iterator, raise an error
																							raise ValueError(
																							    F'''Cannot set key/value for {element}. It needs to be a tuple (key, value).'''     )
																				break
																	setattr(self,  element[0],  element[1]     )
																	if element[1] is not None:
																				lowerCamelCase__		:		str			=element[1]
											elif first_field is not None:
														lowerCamelCase__		:		Dict			=first_field
								else:
											for field in class_fields:
														lowerCamelCase__		:		Union[str, Any]			=getattr(self,  field.name     )
														if v is not None:
																	lowerCamelCase__		:		Optional[int]			=v



					def __delitem__(       self							:  int,  *lowerCamelCase							:  List[str],  **lowerCamelCase							:  Optional[int]     )->					str:
								raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''     )



					def 		snake_case       (       self							:  Optional[int],  *lowerCamelCase							:  int,  **lowerCamelCase							:  List[str]     )->					Optional[Any]:
								raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''     )



					def 		snake_case       (       self							:  Dict,  *lowerCamelCase							:  Optional[int],  **lowerCamelCase							:  Optional[Any]     )->					int:
								raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''     )



					def 		snake_case       (       self							:  List[Any],  *lowerCamelCase							:  Tuple,  **lowerCamelCase							:  List[Any]     )->					Optional[int]:
								raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''     )



					def __getitem__(       self							:  Optional[Any],  lowerCamelCase							:  Optional[int]     )->					List[Any]:
								if isinstance(lowerCamelCase,  lowerCamelCase     ):
											lowerCamelCase__		:		Union[str, Any]			=dict(self.items()     )
											return inner_dict[k]
								else:
											return self.to_tuple()[k]



					def __setattr__(       self							:  Union[str, Any],  lowerCamelCase							:  List[str],  lowerCamelCase							:  List[str]     )->					Dict:
								if name in self.keys() and value is not None:
											# Don't call self.__setitem__ to avoid recursion errors
											super().__setitem__(lowerCamelCase,  lowerCamelCase     )
								super().__setattr__(lowerCamelCase,  lowerCamelCase     )



					def __setitem__(       self							:  Optional[Any],  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  int     )->					List[Any]:
								# Will raise a KeyException if needed
								super().__setitem__(lowerCamelCase,  lowerCamelCase     )
								# Don't call self.__setattr__ to avoid recursion errors
								super().__setattr__(lowerCamelCase,  lowerCamelCase     )




					def 		snake_case       (       self							:  str     )->					Tuple[Any]:
								return tuple(self[k] for k in self.keys()     )





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_		,   lowerCAmelCase_   ):


					'''simple docstring'''





					@classmethod
					def 		snake_case       (       cls							:  Optional[Any],  lowerCamelCase							:  int     )->					str:
								raise ValueError(
								    F'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()     )}'''     )





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'longest'
					_a   			=							'max_length'
					_a   			=							'do_not_pad'





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'pt'
					_a   			=							'tf'
					_a   			=							'np'
					_a   			=							'jax'





class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





					def __init__(       self							:  Optional[int],  lowerCamelCase							:  List[ContextManager]     )->					str:
								lowerCamelCase__		:		List[str]			=context_managers
								lowerCamelCase__		:		int			=ExitStack()



					def __enter__(       self							:  List[str]     )->					Union[str, Any]:
								for context_manager in self.context_managers:
											self.stack.enter_context(lowerCamelCase     )




					def __exit__(       self							:  Tuple,  *lowerCamelCase							:  Union[str, Any],  **lowerCamelCase							:  Tuple     )->					List[Any]:
								self.stack.__exit__(*lowerCamelCase,  **lowerCamelCase     )






def      snake_case__   (		__lowerCamelCase				:    int	):
			"""simple docstring"""
			lowerCamelCase__		:		Tuple			=infer_framework(__lowerCamelCase	)
			if framework == "tf":
						lowerCamelCase__		:		Any			=inspect.signature(model_class.call	)  # TensorFlow models
			elif framework == "pt":
						lowerCamelCase__		:		Tuple			=inspect.signature(model_class.forward	)  # PyTorch models
			else:
						lowerCamelCase__		:		List[str]			=inspect.signature(model_class.__call__	)  # Flax models

			for p in signature.parameters:
						if p == "return_loss" and signature.parameters[p].default is True:
									return True

			return False






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Optional[Any]			=model_class.__name__
			lowerCamelCase__		:		Tuple			=infer_framework(__lowerCamelCase	)
			if framework == "tf":
						lowerCamelCase__		:		int			=inspect.signature(model_class.call	)  # TensorFlow models
			elif framework == "pt":
						lowerCamelCase__		:		Any			=inspect.signature(model_class.forward	)  # PyTorch models
			else:
						lowerCamelCase__		:		Union[str, Any]			=inspect.signature(model_class.__call__	)  # Flax models

			if "QuestionAnswering" in model_name:
						return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
			else:
						return [p for p in signature.parameters if "label" in p]






def      snake_case__   (		__lowerCamelCase				:    MutableMapping							,		__lowerCamelCase				:    str = ""							,		__lowerCamelCase				:    str = "."	):
			"""simple docstring"""

			def _flatten_dict(__lowerCamelCase				:    Optional[int]							,		__lowerCamelCase				:    Optional[int]=""							,		__lowerCamelCase				:    str="."	):
						for k, v in d.items():
									lowerCamelCase__		:		List[str]			=str(__lowerCamelCase	) + delimiter + str(__lowerCamelCase	) if parent_key else k
									if v and isinstance(__lowerCamelCase							,		__lowerCamelCase	):
												yield from flatten_dict(__lowerCamelCase							,		__lowerCamelCase							,		delimiter=__lowerCamelCase	).items()
									else:
												yield key, v

			return dict(_flatten_dict(__lowerCamelCase							,		__lowerCamelCase							,		__lowerCamelCase	)	)






@contextmanager
def      snake_case__   (		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    bool = False	):
			"""simple docstring"""
			if use_temp_dir:
						with tempfile.TemporaryDirectory() as tmp_dir:
									yield tmp_dir
			else:
						yield working_dir






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]							,		__lowerCamelCase				:    Dict=None	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.transpose(__lowerCamelCase							,		axes=__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.T if axes is None else array.permute(*__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.transpose(__lowerCamelCase							,		perm=__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.transpose(__lowerCamelCase							,		axes=__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for transpose: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]							,		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.reshape(__lowerCamelCase							,		__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.reshape(*__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.reshape(__lowerCamelCase							,		__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.reshape(__lowerCamelCase							,		__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for reshape: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]							,		__lowerCamelCase				:    List[str]=None	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.squeeze(__lowerCamelCase							,		axis=__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.squeeze() if axis is None else array.squeeze(dim=__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.squeeze(__lowerCamelCase							,		axis=__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.squeeze(__lowerCamelCase							,		axis=__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for squeeze: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Dict							,		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.expand_dims(__lowerCamelCase							,		__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.unsqueeze(dim=__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.expand_dims(__lowerCamelCase							,		axis=__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.expand_dims(__lowerCamelCase							,		axis=__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for expand_dims: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.size(__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.numel()
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.size(__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return array.size
			else:
						raise ValueError(f'''Type not supported for expand_dims: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Union[str, Any]							,		__lowerCamelCase				:    Tuple	):
			"""simple docstring"""
			for key, value in auto_map.items():
						if isinstance(__lowerCamelCase							,		(tuple, list)	):
									lowerCamelCase__		:		Optional[int]			=[f'''{repo_id}--{v}''' if (v is not None and '''--''' not in v) else v for v in value]
						elif value is not None and "--" not in value:
									lowerCamelCase__		:		Tuple			=f'''{repo_id}--{value}'''

			return auto_map






def      snake_case__   (		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			for base_class in inspect.getmro(__lowerCamelCase	):
						lowerCamelCase__		:		Tuple			=base_class.__module__
						lowerCamelCase__		:		Tuple			=base_class.__name__
						if module.startswith('''tensorflow'''	) or module.startswith('''keras'''	) or name == "TFPreTrainedModel":
									return "tf"
						elif module.startswith('''torch'''	) or name == "PreTrainedModel":
									return "pt"
						elif module.startswith('''flax'''	) or module.startswith('''jax'''	) or name == "FlaxPreTrainedModel":
									return "flax"
			else:
						raise TypeError(f'''Could not infer framework from class {model_class}.'''	)




