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 			A__   :




   """simple docstring"""



   def __init__( self ,  lowercase ,  lowercase=2 ,  lowercase=3 ,  lowercase=4 ,  lowercase=2 ,  lowercase=7 ,  lowercase=True ,  lowercase=True ,  lowercase=True ,  lowercase=True ,  lowercase=99 ,  lowercase=36 ,  lowercase=3 ,  lowercase=4 ,  lowercase=37 ,  lowercase="gelu" ,  lowercase=0.1 ,  lowercase=0.1 ,  lowercase=512 ,  lowercase=16 ,  lowercase=2 ,  lowercase=0.02 ,  lowercase=6 ,  lowercase=6 ,  lowercase=3 ,  lowercase=4 ,  lowercase=None ,  lowercase=1000 ,  )      ->						Union[str, Any]:







          '''simple docstring'''

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

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

   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Optional[int]			=    ids_tensor([self.batch_size, self.text_seq_length] ,  self.vocab_size)

          a__						:     Dict			=    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]:
                               a__						:     Any			=    bbox[i, j, 3]
                               a__						:     int			=    bbox[i, j, 1]
                               a__						:     int			=    t
                        if bbox[i, j, 2] < bbox[i, j, 0]:
                               a__						:     Optional[int]			=    bbox[i, j, 2]
                               a__						:     List[Any]			=    bbox[i, j, 0]
                               a__						:     Optional[int]			=    t

          a__						:     Union[str, Any]			=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          a__						:     Optional[int]			=    None
          if self.use_input_mask:
                 a__						:     List[str]			=    random_attention_mask([self.batch_size, self.text_seq_length])

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

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

          a__						:     str			=    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 ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     List[Any]			=    LayoutLMvaModel(config=_A)
          model.to(_A)
          model.eval()

          # text + image
          a__						:     List[str]			=    model(_A ,  pixel_values=_A)
          a__						:     Tuple			=    model(
              _A ,  bbox=_A ,  pixel_values=_A ,  attention_mask=_A ,  token_type_ids=_A)
          a__						:     Any			=    model(_A ,  bbox=_A ,  pixel_values=_A ,  token_type_ids=_A)
          a__						:     Dict			=    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
          a__						:     Any			=    model(_A)
          self.parent.assertEqual(
              result.last_hidden_state.shape ,  (self.batch_size, self.text_seq_length, self.hidden_size))

          # image only
          a__						:     str			=    model(pixel_values=_A)
          self.parent.assertEqual(
              result.last_hidden_state.shape ,  (self.batch_size, self.image_seq_length, self.hidden_size))

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     List[str]			=    self.num_labels
          a__						:     List[Any]			=    LayoutLMvaForSequenceClassification(_A)
          model.to(_A)
          model.eval()
          a__						:     Optional[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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						str:







          '''simple docstring'''

          a__						:     Optional[int]			=    self.num_labels
          a__						:     List[Any]			=    LayoutLMvaForTokenClassification(config=_A)
          model.to(_A)
          model.eval()
          a__						:     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.text_seq_length, self.num_labels))

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						Tuple:







          '''simple docstring'''

          a__						:     Any			=    LayoutLMvaForQuestionAnswering(config=_A)
          model.to(_A)
          model.eval()
          a__						:     Optional[int]			=    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 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Dict			=    self.prepare_config_and_inputs()
          (
              a__
          )						:     Optional[Any]			=    config_and_inputs
          a__						:     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 			A__   (							snake_case_			,  snake_case_			,  unittest.TestCase     ):




   """simple docstring"""



   __A       :    Optional[int]	  =  False
   __A       :    Union[str, Any]	  =  False
   __A       :    Union[str, Any]	  =  False

   __A       :    List[str]	  =  (
       (
           LayoutLMvaModel,
           LayoutLMvaForSequenceClassification,
           LayoutLMvaForTokenClassification,
           LayoutLMvaForQuestionAnswering,
       )
       if is_torch_available()
       else ()
   )
   __A       :    str	  =  (
       {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel}
       if is_torch_available()
       else {}
   )

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						str:







          '''simple docstring'''

          return True

   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Any			=    LayoutLMvaModelTester(self)
          a__						:     Any			=    ConfigTester(self ,  config_class=_A ,  hidden_size=37)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase=False)      ->						List[str]:







          '''simple docstring'''

          a__						:     List[str]			=    copy.deepcopy(_A)
          if model_class in get_values(_A):
                 a__						:     Optional[int]			=    {
                     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):
                        a__						:     Any			=    torch.ones(self.model_tester.batch_size ,  dtype=torch.long ,  device=_A)
                 elif model_class in get_values(_A):
                        a__						:     List[Any]			=    torch.zeros(
                            self.model_tester.batch_size ,  dtype=torch.long ,  device=_A)
                        a__						:     str			=    torch.zeros(
                            self.model_tester.batch_size ,  dtype=torch.long ,  device=_A)
                 elif model_class in [
                     *get_values(_A),
                 ]:
                        a__						:     List[str]			=    torch.zeros(
                            self.model_tester.batch_size ,  dtype=torch.long ,  device=_A)
                 elif model_class in [
                     *get_values(_A),
                 ]:
                        a__						:     List[Any]			=    torch.zeros(
                            (self.model_tester.batch_size, self.model_tester.text_seq_length) ,  dtype=torch.long ,  device=_A ,  )

          return inputs_dict

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     str			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_A)

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__						:     Tuple			=    self.model_tester.prepare_config_and_inputs()
          for type in ["absolute", "relative_key", "relative_key_query"]:
                 a__						:     str			=    type
                 self.model_tester.create_and_check_model(*_A)

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          a__						:     List[str]			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_sequence_classification(*_A)

   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          a__						:     Optional[int]			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(*_A)

   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     Optional[int]			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_question_answering(*_A)

   @slow
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:     str			=    LayoutLMvaModel.from_pretrained(_A)
                 self.assertIsNotNone(_A)



def A_     (		)  ->		int:
       a__						:     List[Any]			=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
       return image





@require_torch
class 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   @cached_property
   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

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

   @slow
   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__						:     int			=    LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base').to(_A)

          a__						:     Optional[int]			=    self.default_image_processor
          a__						:     Optional[int]			=    prepare_img()
          a__						:     Optional[Any]			=    image_processor(images=_A ,  return_tensors='pt').pixel_values.to(_A)

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

          # forward pass
          a__						:     int			=    model(
              input_ids=input_ids.to(_A) ,  bbox=bbox.to(_A) ,  pixel_values=pixel_values.to(_A) ,  )

          # verify the logits
          a__						:     Any			=    torch.Size((1, 199, 768))
          self.assertEqual(outputs.last_hidden_state.shape ,  _A)

          a__						:     Optional[Any]			=    torch.tensor(
              [[-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]]).to(_A)

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









import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


lowercase				:	str      						=  logging.get_logger(__name__)

lowercase				:	Optional[int]      						=  list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
lowercase				:	str      						=  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)





@dataclass
class 			A__   :




   """simple docstring"""



   __A       :    str	  =  field(
       default=__UpperCAmelCase			,  metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(__UpperCAmelCase     )}     )
   __A       :    str	  =  field(
       default=__UpperCAmelCase			,  metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}     )
   __A       :    int	  =  field(
       default=1_2_8			,  metadata={
           '''help''': (
               '''The maximum total input sequence length after tokenization. Sequences longer '''
               '''than this will be truncated, sequences shorter will be padded.'''
           )
       }			,  )
   __A       :    int	  =  field(
       default=1_2_8			,  metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}			,  )
   __A       :    int	  =  field(
       default=6_4			,  metadata={
           '''help''': (
               '''The maximum number of tokens for the question. Questions longer than this will '''
               '''be truncated to this length.'''
           )
       }			,  )
   __A       :    int	  =  field(
       default=3_0			,  metadata={
           '''help''': (
               '''The maximum length of an answer that can be generated. This is needed because the start '''
               '''and end predictions are not conditioned on one another.'''
           )
       }			,  )
   __A       :    bool	  =  field(
       default=__UpperCAmelCase			,  metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}     )
   __A       :    bool	  =  field(
       default=__UpperCAmelCase			,  metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}     )
   __A       :    float	  =  field(
       default=0.0			,  metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}     )
   __A       :    int	  =  field(
       default=2_0			,  metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}     )
   __A       :    int	  =  field(
       default=0			,  metadata={
           '''help''': (
               '''language id of input for language-specific xlm models (see'''
               ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
           )
       }			,  )
   __A       :    int	  =  field(default=1			,  metadata={'''help''': '''multiple threads for converting example to features'''}     )





class 			A__   (							__UpperCAmelCase     ):




   """simple docstring"""



   __A       :    Dict	  =  '''train'''
   __A       :    Tuple	  =  '''dev'''





class 			A__   (							__UpperCAmelCase     ):




   """simple docstring"""



   __A       :    SquadDataTrainingArguments
   __A       :    List[SquadFeatures]
   __A       :    Split
   __A       :    bool

   def __init__( self ,  lowercase ,  lowercase ,  lowercase = None ,  lowercase = Split.train ,  lowercase = False ,  lowercase = None ,  lowercase = "pt" ,  )      ->						str:







          '''simple docstring'''

          a__						:     List[str]			=    args
          a__						:     Any			=    is_language_sensitive
          a__						:     Optional[Any]			=    SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
          if isinstance(lowercase ,  lowercase):
                 try:
                        a__						:     Optional[int]			=    Split[mode]
                 except KeyError:
                        raise KeyError('mode is not a valid split name')
          a__						:     List[Any]			=    mode
          # Load data features from cache or dataset file
          a__						:     List[str]			=    'v2' if args.version_2_with_negative else 'v1'
          a__						:     Optional[Any]			=    os.path.join(
              cache_dir if cache_dir is not None else args.data_dir ,  F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}' ,  )

          # Make sure only the first process in distributed training processes the dataset,
          # and the others will use the cache.
          a__						:     List[Any]			=    cached_features_file + '.lock'
          with FileLock(lowercase):
                 if os.path.exists(lowercase) and not args.overwrite_cache:
                        a__						:     List[Any]			=    time.time()
                        a__						:     Optional[Any]			=    torch.load(lowercase)

                        # Legacy cache files have only features, while new cache files
                        # will have dataset and examples also.
                        a__						:     List[str]			=    self.old_features['features']
                        a__						:     int			=    self.old_features.get('dataset' ,  lowercase)
                        a__						:     Dict			=    self.old_features.get('examples' ,  lowercase)
                        logger.info(
                            F'Loading features from cached file {cached_features_file} [took %.3f s]' ,  time.time() - start)

                        if self.dataset is None or self.examples is None:
                               logger.warning(
                                   F'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
                                   ' future run')
                 else:
                        if mode == Split.dev:
                               a__						:     Dict			=    self.processor.get_dev_examples(args.data_dir)
                        else:
                               a__						:     int			=    self.processor.get_train_examples(args.data_dir)

                        a__			,							a__						:     Any			=    squad_convert_examples_to_features(
                            examples=self.examples ,  tokenizer=lowercase ,  max_seq_length=args.max_seq_length ,  doc_stride=args.doc_stride ,  max_query_length=args.max_query_length ,  is_training=mode == Split.train ,  threads=args.threads ,  return_dataset=lowercase ,  )

                        a__						:     Tuple			=    time.time()
                        torch.save(
                            {'features': self.features, 'dataset': self.dataset, 'examples': self.examples} ,  lowercase ,  )
                        # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                        logger.info(
                            F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]')

   def __len__( self)      ->						Tuple:







          '''simple docstring'''

          return len(self.features)

   def __getitem__( self ,  lowercase)      ->						Dict[str, torch.Tensor]:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    self.features[i]

          a__						:     Optional[int]			=    torch.tensor(feature.input_ids ,  dtype=torch.long)
          a__						:     Tuple			=    torch.tensor(feature.attention_mask ,  dtype=torch.long)
          a__						:     Optional[Any]			=    torch.tensor(feature.token_type_ids ,  dtype=torch.long)
          a__						:     str			=    torch.tensor(feature.cls_index ,  dtype=torch.long)
          a__						:     Optional[Any]			=    torch.tensor(feature.p_mask ,  dtype=torch.float)
          a__						:     Tuple			=    torch.tensor(feature.is_impossible ,  dtype=torch.float)

          a__						:     str			=    {
              'input_ids': input_ids,
              'attention_mask': attention_mask,
              'token_type_ids': token_type_ids,
          }

          if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
                 del inputs["token_type_ids"]

          if self.args.model_type in ["xlnet", "xlm"]:
                 inputs.update({'cls_index': cls_index, 'p_mask': p_mask})
                 if self.args.version_2_with_negative:
                        inputs.update({'is_impossible': is_impossible})
                 if self.is_language_sensitive:
                        inputs.update({'langs': (torch.ones(input_ids.shape ,  dtype=torch.intaa) * self.args.lang_id)})

          if self.mode == Split.train:
                 a__						:     Dict			=    torch.tensor(feature.start_position ,  dtype=torch.long)
                 a__						:     str			=    torch.tensor(feature.end_position ,  dtype=torch.long)
                 inputs.update({'start_positions': start_positions, 'end_positions': end_positions})

          return inputs


