
"""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 			__magic_name__       :
       def __init__(     self ,				A_ ,				A_=2 ,				A_=3 ,				A_=4 ,				A_=2 ,				A_=7 ,				A_=True ,				A_=True ,				A_=True ,				A_=True ,				A_=99 ,				A_=36 ,				A_=2 ,				A_=4 ,				A_=37 ,				A_="gelu" ,				A_=0.1 ,				A_=0.1 ,				A_=512 ,				A_=16 ,				A_=2 ,				A_=0.02 ,				A_=6 ,				A_=6 ,				A_=3 ,				A_=4 ,				A_=None ,				A_=1000 ,				)     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			Any       =     parent
         _lowercase:			Any       =     batch_size
         _lowercase:			Optional[int]       =     num_channels
         _lowercase:			Dict       =     image_size
         _lowercase:			str       =     patch_size
         _lowercase:			Optional[Any]       =     is_training
         _lowercase:			str       =     use_input_mask
         _lowercase:			List[Any]       =     use_token_type_ids
         _lowercase:			List[Any]       =     use_labels
         _lowercase:			str       =     vocab_size
         _lowercase:			Dict       =     hidden_size
         _lowercase:			Dict       =     num_hidden_layers
         _lowercase:			Optional[Any]       =     num_attention_heads
         _lowercase:			List[str]       =     intermediate_size
         _lowercase:			Tuple       =     hidden_act
         _lowercase:			int       =     hidden_dropout_prob
         _lowercase:			Optional[int]       =     attention_probs_dropout_prob
         _lowercase:			Union[str, Any]       =     max_position_embeddings
         _lowercase:			List[Any]       =     type_vocab_size
         _lowercase:			Dict       =     type_sequence_label_size
         _lowercase:			List[str]       =     initializer_range
         _lowercase:			str       =     coordinate_size
         _lowercase:			Any       =     shape_size
         _lowercase:			Optional[int]       =     num_labels
         _lowercase:			List[str]       =     num_choices
         _lowercase:			Union[str, Any]       =     scope
         _lowercase:			Tuple       =     range_bbox

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





         """simple docstring"""




         _lowercase:			List[str]       =     ids_tensor([self.batch_size, self.text_seq_length] ,				self.vocab_size       )

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

         _lowercase:			Optional[Any]       =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

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

         _lowercase:			Dict       =     None
         _lowercase:			Tuple       =     None
         if self.use_labels:
           _lowercase:			str       =     ids_tensor([self.batch_size] ,				self.type_sequence_label_size       )
           _lowercase:			Optional[int]       =     ids_tensor([self.batch_size, self.text_seq_length] ,				self.num_labels       )

         _lowercase:			Optional[int]       =     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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Dict:





         """simple docstring"""




         _lowercase:			Optional[int]       =     TFLayoutLMvaModel(config=A_       )

         # text + image
         _lowercase:			Optional[Any]       =     model(A_ ,				pixel_values=A_ ,				training=A_       )
         _lowercase:			Optional[Any]       =     model(
             A_ ,				bbox=A_ ,				pixel_values=A_ ,				attention_mask=A_ ,				token_type_ids=A_ ,				training=A_ ,				)
         _lowercase:			Any       =     model(A_ ,				bbox=A_ ,				pixel_values=A_ ,				training=A_       )

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

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

         # image only
         _lowercase:			Optional[Any]       =     model({'''pixel_values''': pixel_values} ,				training=A_       )
         self.parent.assertEqual(
             result.last_hidden_state.shape ,				(self.batch_size, self.image_seq_length, self.hidden_size)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			str       =     self.num_labels
         _lowercase:			int       =     TFLayoutLMvaForSequenceClassification(config=A_       )
         _lowercase:			Union[str, Any]       =     model(
             A_ ,				bbox=A_ ,				pixel_values=A_ ,				attention_mask=A_ ,				token_type_ids=A_ ,				labels=A_ ,				training=A_ ,				)
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Any:





         """simple docstring"""




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





         """simple docstring"""




         _lowercase:			Dict       =     2
         _lowercase:			int       =     TFLayoutLMvaForQuestionAnswering(config=A_       )
         _lowercase:			Any       =     model(
             A_ ,				bbox=A_ ,				pixel_values=A_ ,				attention_mask=A_ ,				token_type_ids=A_ ,				start_positions=A_ ,				end_positions=A_ ,				training=A_ ,				)
         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 							lowercase_							(     self       )     ->	Optional[int]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     self.prepare_config_and_inputs()
         ((_lowercase) ,				(_lowercase) ,				(_lowercase) ,				(_lowercase) ,				(_lowercase) ,				(_lowercase) ,				(_lowercase) ,				(_lowercase)):			Dict       =     config_and_inputs
         _lowercase:			Union[str, Any]       =     {
             '''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 			__magic_name__       (       SCREAMING_SNAKE_CASE__   ,					SCREAMING_SNAKE_CASE__   ,					unittest.TestCase ):
       UpperCamelCase_   =		(
           (
               TFLayoutLMvaModel,
               TFLayoutLMvaForQuestionAnswering,
               TFLayoutLMvaForSequenceClassification,
               TFLayoutLMvaForTokenClassification,
           )
           if is_tf_available()
           else ()
       )
       UpperCamelCase_   =		(
           {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
           if is_tf_available()
           else {}
       )

       UpperCamelCase_   =		False
       UpperCamelCase_   =		False
       UpperCamelCase_   =		False
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Tuple:





         """simple docstring"""




         return True
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_=False       )     ->	dict:





         """simple docstring"""




         _lowercase:			Dict       =     copy.deepcopy(A_       )

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

         if return_labels:
           if model_class in get_values(A_       ):
             _lowercase:			List[str]       =     tf.ones(self.model_tester.batch_size ,				dtype=tf.intaa       )
           elif model_class in get_values(A_       ):
             _lowercase:			List[str]       =     tf.zeros(self.model_tester.batch_size ,				dtype=tf.intaa       )
             _lowercase:			Any       =     tf.zeros(self.model_tester.batch_size ,				dtype=tf.intaa       )
           elif model_class in get_values(A_       ):
             _lowercase:			Dict       =     tf.zeros(self.model_tester.batch_size ,				dtype=tf.intaa       )
           elif model_class in get_values(A_       ):
             _lowercase:			Union[str, Any]       =     tf.zeros(
                 (self.model_tester.batch_size, self.model_tester.text_seq_length) ,				dtype=tf.intaa       )

         return inputs_dict
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     TFLayoutLMvaModelTester(self       )
         _lowercase:			str       =     ConfigTester(self ,				config_class=A_ ,				hidden_size=37       )
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         self.config_tester.run_common_tests()
       def 							lowercase_							(     self       )     ->	Dict:





         """simple docstring"""




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

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

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

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

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

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

             for index, value in sorted_tuple_index_mapping:
               _lowercase:			Tuple       =     prepared_for_class[value]

             _lowercase:			str       =     tuple(A_       )

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

             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]       )
       def 							lowercase_							(     self       )     ->	Any:





         """simple docstring"""




         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			Optional[Any]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			Optional[int]       =     self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
           _lowercase:			int       =     type
           self.model_tester.create_and_check_model(A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			List[str]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(
             A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			Dict       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(
             A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			Tuple       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(
             A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )



       @slow
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowercase:			List[str]       =     TFLayoutLMvaModel.from_pretrained(A_       )
           self.assertIsNotNone(A_       )




def  _lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:			List[Any]       =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
  return image







@require_tf
class 			__magic_name__       (       unittest.TestCase ):
       @cached_property
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         return LayoutLMvaImageProcessor(apply_ocr=A_       ) if is_vision_available() else None



       @slow
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Dict       =     TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''       )

         _lowercase:			Optional[int]       =     self.default_image_processor
         _lowercase:			Tuple       =     prepare_img()
         _lowercase:			List[str]       =     image_processor(images=A_ ,				return_tensors='''tf'''       ).pixel_values

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

         # forward pass
         _lowercase:			Union[str, Any]       =     model(input_ids=A_ ,				bbox=A_ ,				pixel_values=A_ ,				training=A_       )

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

         _lowercase:			Union[str, Any]       =     tf.constant(
             [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]]       )

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


"""simple docstring"""




def  _lowerCAmelCase		(		_UpperCamelCase						):






  """simple docstring"""



  if num <= 0:
    raise ValueError('''Input must be a positive integer'''						)

  _lowercase:			Tuple       =     [True] * (num + 1)

  _lowercase:			List[str]       =     2
  while p * p <= num:
    if primes[p]:
      for i in range(p * p ,				num + 1 ,				_UpperCamelCase						):
        _lowercase:			List[str]       =     False
    p += 1

  return [prime for prime in range(2 ,				num + 1						) if primes[prime]]


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  A__   :					List[Any]							=   int(input('Enter a positive integer: ').strip())
  print(prime_sieve_eratosthenes(user_num))
