
'''simple docstring'''






import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
     MODEL_FOR_QUESTION_ANSWERING_MAPPING,
     MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
     MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
     LayoutLMvaConfig,
     LayoutLMvaForQuestionAnswering,
     LayoutLMvaForSequenceClassification,
     LayoutLMvaForTokenClassification,
     LayoutLMvaModel,
 )
 from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
 from PIL import Image

 from transformers import LayoutLMvaImageProcessor

class  UpperCAmelCase__						:



    def __init__(	self      :       str,__A      :       Tuple,__A      :       int=2,__A      :       List[str]=3,__A      :       Dict=4,__A      :       str=2,__A      :       Tuple=7,__A      :       List[str]=True,__A      :       int=True,__A      :       List[Any]=True,__A      :       Tuple=True,__A      :       Optional[Any]=9_9,__A      :       Optional[int]=3_6,__A      :       str=3,__A      :       Tuple=4,__A      :       Tuple=3_7,__A      :       Any="gelu",__A      :       Any=0.1,__A      :       Any=0.1,__A      :       Optional[int]=5_1_2,__A      :       Optional[int]=1_6,__A      :       int=2,__A      :       str=0.02,__A      :       Optional[int]=6,__A      :       Dict=6,__A      :       Optional[Any]=3,__A      :       Any=4,__A      :       int=None,__A      :       List[Any]=1_0_0_0,):
          _lowerCamelCase				:   Union[str, Any]								=   parent
          _lowerCamelCase				:   List[str]								=   batch_size
          _lowerCamelCase				:   Optional[int]								=   num_channels
          _lowerCamelCase				:   str								=   image_size
          _lowerCamelCase				:   Dict								=   patch_size
          _lowerCamelCase				:   Any								=   text_seq_length
          _lowerCamelCase				:   str								=   is_training
          _lowerCamelCase				:   Any								=   use_input_mask
          _lowerCamelCase				:   Dict								=   use_token_type_ids
          _lowerCamelCase				:   Dict								=   use_labels
          _lowerCamelCase				:   Optional[int]								=   vocab_size
          _lowerCamelCase				:   Any								=   hidden_size
          _lowerCamelCase				:   Tuple								=   num_hidden_layers
          _lowerCamelCase				:   Union[str, Any]								=   num_attention_heads
          _lowerCamelCase				:   Optional[Any]								=   intermediate_size
          _lowerCamelCase				:   int								=   hidden_act
          _lowerCamelCase				:   Any								=   hidden_dropout_prob
          _lowerCamelCase				:   Union[str, Any]								=   attention_probs_dropout_prob
          _lowerCamelCase				:   Dict								=   max_position_embeddings
          _lowerCamelCase				:   Tuple								=   type_vocab_size
          _lowerCamelCase				:   Optional[Any]								=   type_sequence_label_size
          _lowerCamelCase				:   Optional[int]								=   initializer_range
          _lowerCamelCase				:   Union[str, Any]								=   coordinate_size
          _lowerCamelCase				:   int								=   shape_size
          _lowerCamelCase				:   Dict								=   num_labels
          _lowerCamelCase				:   Any								=   num_choices
          _lowerCamelCase				:   List[Any]								=   scope
          _lowerCamelCase				:   List[Any]								=   range_bbox

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



    def   lowerCamelCase_  (	self      :       Tuple     ):
          _lowerCamelCase				:   Dict								=   ids_tensor([self.batch_size, self.text_seq_length],self.vocab_size     )

          _lowerCamelCase				:   Union[str, Any]								=   ids_tensor([self.batch_size, self.text_seq_length, 4],self.range_bbox     )
          # 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				:   Optional[Any]								=   bbox[i, j, 3]
                            _lowerCamelCase				:   Tuple								=   bbox[i, j, 1]
                            _lowerCamelCase				:   List[str]								=   t
                      if bbox[i, j, 2] < bbox[i, j, 0]:
                            _lowerCamelCase				:   Union[str, Any]								=   bbox[i, j, 2]
                            _lowerCamelCase				:   Optional[Any]								=   bbox[i, j, 0]
                            _lowerCamelCase				:   Optional[int]								=   t

          _lowerCamelCase				:   Dict								=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

          _lowerCamelCase				:   Optional[Any]								=   None
          if self.use_input_mask:
                _lowerCamelCase				:   Dict								=   random_attention_mask([self.batch_size, self.text_seq_length]     )

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

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

          _lowerCamelCase				:   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   lowerCamelCase_  (	self      :       Dict,__A      :       int,__A      :       str,__A      :       str,__A      :       List[Any],__A      :       List[Any],__A      :       Any,__A      :       Optional[Any],__A      :       List[Any]     ):
          _lowerCamelCase				:   Union[str, Any]								=   LayoutLMvaModel(config=__A     )
          model.to(__A     )
          model.eval()

          # text + image
          _lowerCamelCase				:   Tuple								=   model(__A,pixel_values=__A     )
          _lowerCamelCase				:   int								=   model(
              __A,bbox=__A,pixel_values=__A,attention_mask=__A,token_type_ids=__A     )
          _lowerCamelCase				:   Optional[Any]								=   model(__A,bbox=__A,pixel_values=__A,token_type_ids=__A     )
          _lowerCamelCase				:   Any								=   model(__A,bbox=__A,pixel_values=__A     )

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

          # text only
          _lowerCamelCase				:   str								=   model(__A     )
          self.parent.assertEqual(
              result.last_hidden_state.shape,(self.batch_size, self.text_seq_length, self.hidden_size)     )

          # image only
          _lowerCamelCase				:   Tuple								=   model(pixel_values=__A     )
          self.parent.assertEqual(
              result.last_hidden_state.shape,(self.batch_size, self.image_seq_length, self.hidden_size)     )



    def   lowerCamelCase_  (	self      :       Tuple,__A      :       Optional[int],__A      :       Any,__A      :       Optional[Any],__A      :       Dict,__A      :       List[Any],__A      :       str,__A      :       List[str],__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   Dict								=   self.num_labels
          _lowerCamelCase				:   Union[str, Any]								=   LayoutLMvaForSequenceClassification(__A     )
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   List[Any]								=   model(
              __A,bbox=__A,pixel_values=__A,attention_mask=__A,token_type_ids=__A,labels=__A,)
          self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)     )



    def   lowerCamelCase_  (	self      :       int,__A      :       int,__A      :       Optional[Any],__A      :       Optional[Any],__A      :       Optional[int],__A      :       Dict,__A      :       str,__A      :       Optional[int],__A      :       Optional[Any]     ):
          _lowerCamelCase				:   List[str]								=   self.num_labels
          _lowerCamelCase				:   str								=   LayoutLMvaForTokenClassification(config=__A     )
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   List[str]								=   model(
              __A,bbox=__A,pixel_values=__A,attention_mask=__A,token_type_ids=__A,labels=__A,)
          self.parent.assertEqual(result.logits.shape,(self.batch_size, self.text_seq_length, self.num_labels)     )



    def   lowerCamelCase_  (	self      :       str,__A      :       int,__A      :       Tuple,__A      :       Tuple,__A      :       Dict,__A      :       Optional[Any],__A      :       Optional[int],__A      :       Union[str, Any],__A      :       List[Any]     ):
          _lowerCamelCase				:   Optional[Any]								=   LayoutLMvaForQuestionAnswering(config=__A     )
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   List[str]								=   model(
              __A,bbox=__A,pixel_values=__A,attention_mask=__A,token_type_ids=__A,start_positions=__A,end_positions=__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   lowerCamelCase_  (	self      :       Optional[int]     ):
          _lowerCamelCase				:   List[str]								=   self.prepare_config_and_inputs()
          (
              (
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		
          )				:   Union[str, Any]								=   config_and_inputs
          _lowerCamelCase				:   Optional[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_torch
class  UpperCAmelCase__						(       A						,	A						,	unittest.TestCase ):
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False

    lowerCAmelCase_				    =		(
        (
            LayoutLMvaModel,
            LayoutLMvaForSequenceClassification,
            LayoutLMvaForTokenClassification,
            LayoutLMvaForQuestionAnswering,
        )
        if is_torch_available()
        else ()
    )
    lowerCAmelCase_				    =		(
        {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel}
        if is_torch_available()
        else {}
    )



    def   lowerCamelCase_  (	self      :       Tuple,__A      :       List[str],__A      :       Tuple,__A      :       Optional[int],__A      :       Optional[Any],__A      :       Tuple     ):
          # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
          # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
          # the sequence dimension of the text embedding only.
          # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
          return True



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   Any								=   LayoutLMvaModelTester(self     )
          _lowerCamelCase				:   List[Any]								=   ConfigTester(self,config_class=__A,hidden_size=3_7     )



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       Optional[int],__A      :       str,__A      :       Dict=False     ):
          _lowerCamelCase				:   List[Any]								=   copy.deepcopy(__A     )
          if model_class in get_values(__A     ):
                _lowerCamelCase				:   Dict								=   {
                    k: v.unsqueeze(1     ).expand(-1,self.model_tester.num_choices,-1     ).contiguous()
                    if isinstance(__A,torch.Tensor     ) and v.ndim > 1
                    else v
                    for k, v in inputs_dict.items()
                }
          if return_labels:
                if model_class in get_values(__A     ):
                      _lowerCamelCase				:   Optional[Any]								=   torch.ones(self.model_tester.batch_size,dtype=torch.long,device=__A     )
                elif model_class in get_values(__A     ):
                      _lowerCamelCase				:   Optional[int]								=   torch.zeros(
                          self.model_tester.batch_size,dtype=torch.long,device=__A     )
                      _lowerCamelCase				:   Optional[Any]								=   torch.zeros(
                          self.model_tester.batch_size,dtype=torch.long,device=__A     )
                elif model_class in [
                    *get_values(__A     ),
                ]:
                      _lowerCamelCase				:   Any								=   torch.zeros(
                          self.model_tester.batch_size,dtype=torch.long,device=__A     )
                elif model_class in [
                    *get_values(__A     ),
                ]:
                      _lowerCamelCase				:   Any								=   torch.zeros(
                          (self.model_tester.batch_size, self.model_tester.text_seq_length),dtype=torch.long,device=__A,)

          return inputs_dict



    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          self.config_tester.run_common_tests()



    def   lowerCamelCase_  (	self      :       str     ):
          _lowerCamelCase				:   Any								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__A     )



    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          _lowerCamelCase				:   Optional[Any]								=   self.model_tester.prepare_config_and_inputs()
          for type in ["absolute", "relative_key", "relative_key_query"]:
                _lowerCamelCase				:   Tuple								=   type
                self.model_tester.create_and_check_model(*__A     )



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   Optional[Any]								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_sequence_classification(*__A     )



    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          _lowerCamelCase				:   int								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(*__A     )



    def   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   Optional[int]								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_question_answering(*__A     )



    @slow
    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _lowerCamelCase				:   Tuple								=   LayoutLMvaModel.from_pretrained(__A     )
                self.assertIsNotNone(__A     )







def 		A_       (	):



      """simple docstring"""




      _lowerCamelCase				:   Optional[int]								=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
      return image



@require_torch
class  UpperCAmelCase__						(       unittest.TestCase ):



    @cached_property
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          return LayoutLMvaImageProcessor(apply_ocr=__A     ) if is_vision_available() else None



    @slow
    def   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   Any								=   LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base"     ).to(__A     )

          _lowerCamelCase				:   Union[str, Any]								=   self.default_image_processor
          _lowerCamelCase				:   List[str]								=   prepare_img()
          _lowerCamelCase				:   Optional[int]								=   image_processor(images=__A,return_tensors="pt"     ).pixel_values.to(__A     )

          _lowerCamelCase				:   str								=   torch.tensor([[1, 2]]     )
          _lowerCamelCase				:   Union[str, Any]								=   torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]     ).unsqueeze(0     )

          # forward pass
          _lowerCamelCase				:   Optional[int]								=   model(
              input_ids=input_ids.to(__A     ),bbox=bbox.to(__A     ),pixel_values=pixel_values.to(__A     ),)

          # verify the logits
          _lowerCamelCase				:   List[str]								=   torch.Size((1, 1_9_9, 7_6_8)     )
          self.assertEqual(outputs.last_hidden_state.shape,__A     )

          _lowerCamelCase				:   int								=   torch.tensor(
              [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]     ).to(__A     )

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

'''simple docstring'''






def 		A_       (	_lowerCAmelCase   :    float							):



      """simple docstring"""




      return 10 - x * x







def 		A_       (	_lowerCAmelCase   :    float				,	_lowerCAmelCase   :    float							):



      """simple docstring"""




      if equation(_lowerCAmelCase							) * equation(_lowerCAmelCase							) >= 0:
            raise ValueError("Wrong space!"							)

      _lowerCamelCase				:   List[str]								=   a
      while (b - a) >= 0.0_1:
            # Find middle point
            _lowerCamelCase				:   Union[str, Any]								=   (a + b) / 2
            # Check if middle point is root
            if equation(_lowerCAmelCase							) == 0.0:
                  break
            # Decide the side to repeat the steps
            if equation(_lowerCAmelCase							) * equation(_lowerCAmelCase							) < 0:
                  _lowerCamelCase				:   Union[str, Any]								=   c
            else:
                  _lowerCamelCase				:   Any								=   c
      return c


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 print(bisection(-2, 5))
 print(bisection(0, 6))