

"""simple docstring"""




from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
      from ...processing_utils import ProcessorMixin
      from ...utils import TensorType


__UpperCAmelCase =				logging.get_logger(__name__)

__UpperCAmelCase =				{
    'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json',
}







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       """layoutlmv3"""

  def __init__(  self		:			Dict					,A		:			Union[str, Any]=50_265					,A		:			Optional[Any]=768					,A		:			Optional[int]=12					,A		:			int=12					,A		:			int=3_072					,A		:			Any="gelu"					,A		:			Any=0.1					,A		:			Union[str, Any]=0.1					,A		:			Dict=512					,A		:			Any=2					,A		:			List[str]=0.0_2					,A		:			Optional[int]=1e-5					,A		:			Optional[Any]=1					,A		:			Optional[int]=0					,A		:			Union[str, Any]=2					,A		:			Optional[Any]=1_024					,A		:			int=128					,A		:			List[str]=128					,A		:			Optional[int]=True					,A		:			List[Any]=32					,A		:			List[str]=128					,A		:			Dict=64					,A		:			Optional[int]=256					,A		:			Optional[int]=True					,A		:			List[Any]=True					,A		:			Dict=True					,A		:			Any=224					,A		:			str=3					,A		:			List[str]=16					,A		:			int=None					,**A		:			Any					,):






   '''simple docstring'''
   super().__init__(
       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					,initializer_range=A					,layer_norm_eps=A					,pad_token_id=A					,bos_token_id=A					,eos_token_id=A					,**A					,)
   UpperCAmelCase__					:  Any					   =					max_ad_position_embeddings
   UpperCAmelCase__					:  Dict					   =					coordinate_size
   UpperCAmelCase__					:  Tuple					   =					shape_size
   UpperCAmelCase__					:  Dict					   =					has_relative_attention_bias
   UpperCAmelCase__					:  List[Any]					   =					rel_pos_bins
   UpperCAmelCase__					:  Dict					   =					max_rel_pos
   UpperCAmelCase__					:  List[Any]					   =					has_spatial_attention_bias
   UpperCAmelCase__					:  str					   =					rel_ad_pos_bins
   UpperCAmelCase__					:  Optional[Any]					   =					max_rel_ad_pos
   UpperCAmelCase__					:  Optional[int]					   =					text_embed
   UpperCAmelCase__					:  Any					   =					visual_embed
   UpperCAmelCase__					:  List[str]					   =					input_size
   UpperCAmelCase__					:  Tuple					   =					num_channels
   UpperCAmelCase__					:  Dict					   =					patch_size
   UpperCAmelCase__					:  str					   =					classifier_dropout







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       version.parse("""1.12"""					)

  @property
  def    __lowercase       (  self		:			Tuple    ):






   '''simple docstring'''
   # The order of inputs is different for question answering and sequence classification
   if self.task in ["question-answering", "sequence-classification"]:
    return OrderedDict(
        [
            ("""input_ids""", {0: """batch""", 1: """sequence"""}),
            ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
            ("""bbox""", {0: """batch""", 1: """sequence"""}),
            ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
        ]    )
   else:
    return OrderedDict(
        [
            ("""input_ids""", {0: """batch""", 1: """sequence"""}),
            ("""bbox""", {0: """batch""", 1: """sequence"""}),
            ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
            ("""pixel_values""", {0: """batch""", 1: """num_channels"""}),
        ]    )

  @property
  def    __lowercase       (  self		:			List[Any]    ):






   '''simple docstring'''
   return 1e-5

  @property
  def    __lowercase       (  self		:			Optional[Any]    ):






   '''simple docstring'''
   return 12




  def    __lowercase       (  self		:			List[str]					,A		:			"ProcessorMixin"					,A		:			int = -1					,A		:			int = -1					,A		:			bool = False					,A		:			Optional["TensorType"] = None					,A		:			int = 3					,A		:			int = 40					,A		:			int = 40					,):






   '''simple docstring'''
   setattr(processor.image_processor					,"""apply_ocr"""					,A    )

   # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
   UpperCAmelCase__					:  Optional[int]					   =					compute_effective_axis_dimension(
       A					,fixed_dimension=OnnxConfig.default_fixed_batch					,num_token_to_add=0    )
   # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
   UpperCAmelCase__					:  Tuple					   =					processor.tokenizer.num_special_tokens_to_add(A    )
   UpperCAmelCase__					:  Union[str, Any]					   =					compute_effective_axis_dimension(
       A					,fixed_dimension=OnnxConfig.default_fixed_sequence					,num_token_to_add=A    )
   # Generate dummy inputs according to compute batch and sequence
   UpperCAmelCase__					:  Union[str, Any]					   =					[[""" """.join([processor.tokenizer.unk_token]    ) * seq_length]] * batch_size

   # Generate dummy bounding boxes
   UpperCAmelCase__					:  List[str]					   =					[[[48, 84, 73, 128]]] * batch_size

   # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
   # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
   UpperCAmelCase__					:  Optional[int]					   =					self._generate_dummy_images(A					,A					,A					,A    )

   UpperCAmelCase__					:  Optional[Any]					   =					dict(
       processor(
           A					,text=A					,boxes=A					,return_tensors=A					,)    )

   return inputs








"""simple docstring"""




from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


__UpperCAmelCase =				logging.get_logger(__name__)


__UpperCAmelCase =				TypeVar('DatasetType', Dataset, IterableDataset)
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase = None							,    __UpperCamelCase = None							,    __UpperCamelCase = None							,    __UpperCamelCase = None							,    __UpperCamelCase = "first_exhausted"							,    ):
 '''simple docstring'''





 from .arrow_dataset import Dataset
 from .iterable_dataset import IterableDataset

 if not datasets:
  raise ValueError("""Unable to interleave an empty list of datasets."""      )
 for i, dataset in enumerate(__UpperCamelCase      ):
  if not isinstance(__UpperCamelCase							,    (Dataset, IterableDataset)      ):
   if isinstance(__UpperCamelCase							,    (DatasetDict, IterableDatasetDict)      ):
    if not dataset:
     raise ValueError(
         F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} "
         """is an empty dataset dictionary."""      )
    raise ValueError(
        F"Dataset at position {i} has at least one split: {list(__UpperCamelCase      )}\n"
        F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(__UpperCamelCase      )      )}']"      )
   raise ValueError(
       F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(__UpperCamelCase      ).__name__}."      )
  if i == 0:
   UpperCAmelCase__   ,      UpperCAmelCase__					:  List[str]					   =					(
       (Dataset, IterableDataset) if isinstance(__UpperCamelCase							,    __UpperCamelCase      ) else (IterableDataset, Dataset)
   )
  elif not isinstance(__UpperCamelCase							,    __UpperCamelCase      ):
   raise ValueError(
       F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."      )
 if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
  raise ValueError(F"{stopping_strategy} is not supported. Please enter a valid stopping_strategy."      )
 if dataset_type is Dataset:
  return _interleave_map_style_datasets(
      __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    info=__UpperCamelCase							,    split=__UpperCamelCase							,    stopping_strategy=__UpperCamelCase      )
 else:
  return _interleave_iterable_datasets(
      __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    info=__UpperCamelCase							,    split=__UpperCamelCase							,    stopping_strategy=__UpperCamelCase      )




def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase = None							,    __UpperCamelCase = None							,    __UpperCamelCase = 0							,    ):
 '''simple docstring'''





 if not dsets:
  raise ValueError("""Unable to concatenate an empty list of datasets."""      )
 for i, dataset in enumerate(__UpperCamelCase      ):
  if not isinstance(__UpperCamelCase							,    (Dataset, IterableDataset)      ):
   if isinstance(__UpperCamelCase							,    (DatasetDict, IterableDatasetDict)      ):
    if not dataset:
     raise ValueError(
         F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} "
         """is an empty dataset dictionary."""      )
    raise ValueError(
        F"Dataset at position {i} has at least one split: {list(__UpperCamelCase      )}\n"
        F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(__UpperCamelCase      )      )}']"      )
   raise ValueError(
       F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(__UpperCamelCase      ).__name__}."      )
  if i == 0:
   UpperCAmelCase__   ,      UpperCAmelCase__					:  Optional[int]					   =					(
       (Dataset, IterableDataset) if isinstance(__UpperCamelCase							,    __UpperCamelCase      ) else (IterableDataset, Dataset)
   )
  elif not isinstance(__UpperCamelCase							,    __UpperCamelCase      ):
   raise ValueError(
       F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."      )
 if dataset_type is Dataset:
  return _concatenate_map_style_datasets(__UpperCamelCase							,    info=__UpperCamelCase							,    split=__UpperCamelCase							,    axis=__UpperCamelCase      )
 else:
  return _concatenate_iterable_datasets(__UpperCamelCase							,    info=__UpperCamelCase							,    split=__UpperCamelCase							,    axis=__UpperCamelCase      )





