


"""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 			lowerCamelCase__						:







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

								# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
								A					       = text_seq_length
								A					       = (image_size // patch_size) ** 2 + 1
								A					       = self.text_seq_length + self.image_seq_length







						def __a						(							self   :    Any		):
								A					       = ids_tensor([self.batch_size, self.text_seq_length]			,			self.vocab_size		)

								A					       = ids_tensor([self.batch_size, self.text_seq_length, 4]			,			self.range_bbox		)
								A					       = 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]:
														A					       = bbox[i, j, 3]
														A					       = bbox[i, j, 1]
														A					       = tmp_coordinate
												if bbox[i, j, 2] < bbox[i, j, 0]:
														A					       = bbox[i, j, 2]
														A					       = bbox[i, j, 0]
														A					       = tmp_coordinate
								A					       = tf.constant(_lowercase		)

								A					       = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

								A					       = None
								if self.use_input_mask:
										A					       = random_attention_mask([self.batch_size, self.text_seq_length]		)

								A					       = None
								if self.use_token_type_ids:
										A					       = ids_tensor([self.batch_size, self.text_seq_length]			,			self.type_vocab_size		)

								A					       = None
								A					       = None
								if self.use_labels:
										A					       = ids_tensor([self.batch_size]			,			self.type_sequence_label_size		)
										A					       = ids_tensor([self.batch_size, self.text_seq_length]			,			self.num_labels		)

								A					       = 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 __a						(							self   :    List[str]			,			_lowercase   :    List[str]			,			_lowercase   :    List[Any]			,			_lowercase   :    str			,			_lowercase   :    List[str]			,			_lowercase   :    str			,			_lowercase   :    Optional[Any]		):
								A					       = TFLayoutLMvaModel(config=_lowercase		)

								# text + image
								A					       = model(_lowercase			,			pixel_values=_lowercase			,			training=_lowercase		)
								A					       = model(
								    _lowercase			,			bbox=_lowercase			,			pixel_values=_lowercase			,			attention_mask=_lowercase			,			token_type_ids=_lowercase			,			training=_lowercase			,			)
								A					       = model(_lowercase			,			bbox=_lowercase			,			pixel_values=_lowercase			,			training=_lowercase		)

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

								# text only
								A					       = model(_lowercase			,			training=_lowercase		)
								self.parent.assertEqual(
								    result.last_hidden_state.shape			,			(self.batch_size, self.text_seq_length, self.hidden_size)		)

								# image only
								A					       = model({'pixel_values': pixel_values}			,			training=_lowercase		)
								self.parent.assertEqual(
								    result.last_hidden_state.shape			,			(self.batch_size, self.image_seq_length, self.hidden_size)		)







						def __a						(							self   :    Union[str, Any]			,			_lowercase   :    Tuple			,			_lowercase   :    Union[str, Any]			,			_lowercase   :    Optional[Any]			,			_lowercase   :    int			,			_lowercase   :    Optional[Any]			,			_lowercase   :    Optional[Any]			,			_lowercase   :    Dict		):
								A					       = self.num_labels
								A					       = TFLayoutLMvaForSequenceClassification(config=_lowercase		)
								A					       = model(
								    _lowercase			,			bbox=_lowercase			,			pixel_values=_lowercase			,			attention_mask=_lowercase			,			token_type_ids=_lowercase			,			labels=_lowercase			,			training=_lowercase			,			)
								self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)		)







						def __a						(							self   :    Union[str, Any]			,			_lowercase   :    int			,			_lowercase   :    Union[str, Any]			,			_lowercase   :    List[Any]			,			_lowercase   :    Tuple			,			_lowercase   :    List[str]			,			_lowercase   :    Any			,			_lowercase   :    List[Any]		):
								A					       = self.num_labels
								A					       = TFLayoutLMvaForTokenClassification(config=_lowercase		)
								A					       = model(
								    _lowercase			,			bbox=_lowercase			,			pixel_values=_lowercase			,			attention_mask=_lowercase			,			token_type_ids=_lowercase			,			labels=_lowercase			,			training=_lowercase			,			)
								self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.text_seq_length, self.num_labels)		)







						def __a						(							self   :    Optional[Any]			,			_lowercase   :    List[Any]			,			_lowercase   :    int			,			_lowercase   :    Optional[int]			,			_lowercase   :    Dict			,			_lowercase   :    int			,			_lowercase   :    Tuple			,			_lowercase   :    int		):
								A					       = 2
								A					       = TFLayoutLMvaForQuestionAnswering(config=_lowercase		)
								A					       = model(
								    _lowercase			,			bbox=_lowercase			,			pixel_values=_lowercase			,			attention_mask=_lowercase			,			token_type_ids=_lowercase			,			start_positions=_lowercase			,			end_positions=_lowercase			,			training=_lowercase			,			)
								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 __a						(							self   :    Tuple		):
								A					       = self.prepare_config_and_inputs()
								((A)       , (A)       , (A)       , (A)       , (A)       , (A)       , (A)       , (A))					       = config_and_inputs
								A					       = {
								    '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 			lowerCamelCase__						(   UpperCAmelCase_							,    UpperCAmelCase_							,    unittest.TestCase			):
						lowerCAmelCase       =     (
						    (
						        TFLayoutLMvaModel,
						        TFLayoutLMvaForQuestionAnswering,
						        TFLayoutLMvaForSequenceClassification,
						        TFLayoutLMvaForTokenClassification,
						    )
						    if is_tf_available()
						    else ()
						)
						lowerCAmelCase       =     (
						    {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel}
						    if is_tf_available()
						    else {}
						)

						lowerCAmelCase       =     False
						lowerCAmelCase       =     False
						lowerCAmelCase       =     False







						def __a						(							self   :    List[str]			,			_lowercase   :    str			,			_lowercase   :    List[str]			,			_lowercase   :    Any			,			_lowercase   :    Any			,			_lowercase   :    Union[str, Any]		):
								return True







						def __a						(							self   :    Optional[int]			,			_lowercase   :    str			,			_lowercase   :    List[str]			,			_lowercase   :    Union[str, Any]=False		):
								A					       = copy.deepcopy(_lowercase		)

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

								if return_labels:
										if model_class in get_values(_lowercase		):
												A					       = tf.ones(self.model_tester.batch_size			,			dtype=tf.intaa		)
										elif model_class in get_values(_lowercase		):
												A					       = tf.zeros(self.model_tester.batch_size			,			dtype=tf.intaa		)
												A					       = tf.zeros(self.model_tester.batch_size			,			dtype=tf.intaa		)
										elif model_class in get_values(_lowercase		):
												A					       = tf.zeros(self.model_tester.batch_size			,			dtype=tf.intaa		)
										elif model_class in get_values(_lowercase		):
												A					       = tf.zeros(
												    (self.model_tester.batch_size, self.model_tester.text_seq_length)			,			dtype=tf.intaa		)

								return inputs_dict







						def __a						(							self   :    Dict		):
								A					       = TFLayoutLMvaModelTester(self		)
								A					       = ConfigTester(self			,			config_class=_lowercase			,			hidden_size=37		)







						def __a						(							self   :    Tuple		):
								self.config_tester.run_common_tests()







						def __a						(							self   :    int		):
								A       , A					       = self.model_tester.prepare_config_and_inputs_for_common()
								for model_class in self.all_model_classes:
										A					       = model_class(_lowercase		)
										if getattr(_lowercase			,			'hf_compute_loss'			,			_lowercase		):
												# The number of elements in the loss should be the same as the number of elements in the label
												A					       = self._prepare_for_class(inputs_dict.copy()			,			_lowercase			,			return_labels=_lowercase		)
												A					       = prepared_for_class[
												    sorted(prepared_for_class.keys() - inputs_dict.keys()			,			reverse=_lowercase		)[0]
												]
												A					       = added_label.shape.as_list()[:1]

												# Test that model correctly compute the loss with kwargs
												A					       = self._prepare_for_class(inputs_dict.copy()			,			_lowercase			,			return_labels=_lowercase		)
												A					       = prepared_for_class.pop('input_ids'		)

												A					       = model(_lowercase			,			**_lowercase		)[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
												A					       = self._prepare_for_class(inputs_dict.copy()			,			_lowercase			,			return_labels=_lowercase		)
												A					       = prepared_for_class.pop('input_ids'		)
												if "labels" in prepared_for_class:
														A					       = prepared_for_class['labels'].numpy()
														if len(labels.shape		) > 1 and labels.shape[1] != 1:
																A					       = -100
																A					       = tf.convert_to_tensor(_lowercase		)
																A					       = model(_lowercase			,			**_lowercase		)[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
												A					       = self._prepare_for_class(inputs_dict.copy()			,			_lowercase			,			return_labels=_lowercase		)
												A					       = model(_lowercase		)[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
												A					       = self._prepare_for_class(inputs_dict.copy()			,			_lowercase			,			return_labels=_lowercase		)

												# Get keys that were added with the _prepare_for_class function
												A					       = prepared_for_class.keys() - inputs_dict.keys()
												A					       = inspect.signature(model.call		).parameters
												A					       = list(signature.keys()		)

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

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

												for index, value in sorted_tuple_index_mapping:
														A					       = prepared_for_class[value]

												A					       = tuple(_lowercase		)

												# Send to model
												A					       = model(tuple_input[:-1]		)[0]

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







						def __a						(							self   :    Dict		):
								(
								    (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , 
								)					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase		)







						def __a						(							self   :    str		):
								(
								    (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , 
								)					       = self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
										A					       = type
										self.model_tester.create_and_check_model(_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase		)







						def __a						(							self   :    Union[str, Any]		):
								(
								    (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , 
								)					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(
								    _lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase		)







						def __a						(							self   :    List[str]		):
								(
								    (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , 
								)					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(
								    _lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase		)







						def __a						(							self   :    List[str]		):
								(
								    (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , (
								    A
								)       , 
								)					       = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(
								    _lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			_lowercase		)







						@slow
						def __a						(							self   :    Optional[Any]		):
								for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										A					       = TFLayoutLMvaModel.from_pretrained(_lowercase		)
										self.assertIsNotNone(_lowercase		)







def  __snake_case       (   )      ->		List[Any]:







		"""simple docstring"""





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



@require_tf
class 			lowerCamelCase__						(   unittest.TestCase			):







						@cached_property
						def __a						(							self   :    int		):
								return LayoutLMvaImageProcessor(apply_ocr=_lowercase		) if is_vision_available() else None







						@slow
						def __a						(							self   :    Any		):
								A					       = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'		)

								A					       = self.default_image_processor
								A					       = prepare_img()
								A					       = image_processor(images=_lowercase			,			return_tensors='tf'		).pixel_values

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

								# forward pass
								A					       = model(input_ids=_lowercase			,			bbox=_lowercase			,			pixel_values=_lowercase			,			training=_lowercase		)

								# verify the logits
								A					       = (1, 199, 768)
								self.assertEqual(outputs.last_hidden_state.shape			,			_lowercase		)

								A					       = tf.constant(
								    [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]		)

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









"""simple docstring"""


def  __snake_case       (   UpperCamelCase__ ,			UpperCamelCase__	)      ->		int:







		"""simple docstring"""





		while b:
				A       , A					       = b, a % b
		return a







def  __snake_case       (   UpperCamelCase__ ,			UpperCamelCase__	)      ->		int:







		"""simple docstring"""





		return a if b == 0 else euclidean_gcd_recursive(UpperCamelCase__ ,			a % b	)







def  __snake_case       (   )      ->		List[Any]:







		"""simple docstring"""





		print(f'euclidean_gcd(3, 5) = {euclidean_gcd(3 ,			5	)}'	)
		print(f'euclidean_gcd(5, 3) = {euclidean_gcd(5 ,			3	)}'	)
		print(f'euclidean_gcd(1, 3) = {euclidean_gcd(1 ,			3	)}'	)
		print(f'euclidean_gcd(3, 6) = {euclidean_gcd(3 ,			6	)}'	)
		print(f'euclidean_gcd(6, 3) = {euclidean_gcd(6 ,			3	)}'	)

		print(f'euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 ,			5	)}'	)
		print(f'euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 ,			3	)}'	)
		print(f'euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 ,			3	)}'	)
		print(f'euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 ,			6	)}'	)
		print(f'euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 ,			3	)}'	)


if __name__ == "__main__":
	main()





