


import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType






class   __lowercase				(  __snake_case  ):
      UpperCamelCase								=       ['''image_processor''', '''tokenizer''']
      UpperCamelCase								=       '''LayoutLMv2ImageProcessor'''
      UpperCamelCase								=       ('''LayoutXLMTokenizer''', '''LayoutXLMTokenizerFast''')





      def __init__(		self						:					List[Any]					,       __lowerCamelCase						:					str=None					,       __lowerCamelCase						:					Any=None					,       **__lowerCamelCase						:					Optional[int]       )    ->   List[Any]:






         """simple docstring"""







         if "feature_extractor" in kwargs:
            warnings.warn(
                """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
                """ instead."""					,       __lowerCamelCase					,       )
            UpperCAmelCase							=     kwargs.pop("""feature_extractor"""       )

         UpperCAmelCase							=     image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
            raise ValueError("""You need to specify an `image_processor`."""       )
         if tokenizer is None:
            raise ValueError("""You need to specify a `tokenizer`."""       )

         super().__init__(__lowerCamelCase					,       __lowerCamelCase       )





      def __call__(		self						:					str					,       __lowerCamelCase						:					int					,       __lowerCamelCase						:					Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None					,       __lowerCamelCase						:					Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None					,       __lowerCamelCase						:					Union[List[List[int]], List[List[List[int]]]] = None					,       __lowerCamelCase						:					Optional[Union[List[int], List[List[int]]]] = None					,       __lowerCamelCase						:					bool = True					,       __lowerCamelCase						:					Union[bool, str, PaddingStrategy] = False					,       __lowerCamelCase						:					Union[bool, str, TruncationStrategy] = None					,       __lowerCamelCase						:					Optional[int] = None					,       __lowerCamelCase						:					int = 0					,       __lowerCamelCase						:					Optional[int] = None					,       __lowerCamelCase						:					Optional[bool] = None					,       __lowerCamelCase						:					Optional[bool] = None					,       __lowerCamelCase						:					bool = False					,       __lowerCamelCase						:					bool = False					,       __lowerCamelCase						:					bool = False					,       __lowerCamelCase						:					bool = False					,       __lowerCamelCase						:					bool = True					,       __lowerCamelCase						:					Optional[Union[str, TensorType]] = None					,       **__lowerCamelCase						:					Dict					,       )    ->   BatchEncoding:






         """simple docstring"""







         if self.image_processor.apply_ocr and (boxes is not None):
            raise ValueError(
                """You cannot provide bounding boxes """
                """if you initialized the image processor with apply_ocr set to True."""       )

         if self.image_processor.apply_ocr and (word_labels is not None):
            raise ValueError(
                """You cannot provide word labels if you initialized the image processor with apply_ocr set to True."""       )

         if return_overflowing_tokens is True and return_offsets_mapping is False:
            raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping."""       )

         # first, apply the image processor
         UpperCAmelCase							=     self.image_processor(images=__lowerCamelCase					,       return_tensors=__lowerCamelCase       )

         # second, apply the tokenizer
         if text is not None and self.image_processor.apply_ocr and text_pair is None:
            if isinstance(__lowerCamelCase					,       __lowerCamelCase       ):
               UpperCAmelCase							=     [text]  # add batch dimension (as the image processor always adds a batch dimension)
            UpperCAmelCase							=     features["""words"""]

         UpperCAmelCase							=     self.tokenizer(
             text=text if text is not None else features["""words"""]					,       text_pair=text_pair if text_pair is not None else None					,       boxes=boxes if boxes is not None else features["""boxes"""]					,       word_labels=__lowerCamelCase					,       add_special_tokens=__lowerCamelCase					,       padding=__lowerCamelCase					,       truncation=__lowerCamelCase					,       max_length=__lowerCamelCase					,       stride=__lowerCamelCase					,       pad_to_multiple_of=__lowerCamelCase					,       return_token_type_ids=__lowerCamelCase					,       return_attention_mask=__lowerCamelCase					,       return_overflowing_tokens=__lowerCamelCase					,       return_special_tokens_mask=__lowerCamelCase					,       return_offsets_mapping=__lowerCamelCase					,       return_length=__lowerCamelCase					,       verbose=__lowerCamelCase					,       return_tensors=__lowerCamelCase					,       **__lowerCamelCase					,       )

         # add pixel values
         UpperCAmelCase							=     features.pop("""pixel_values"""       )
         if return_overflowing_tokens is True:
            UpperCAmelCase							=     self.get_overflowing_images(__lowerCamelCase					,       encoded_inputs["""overflow_to_sample_mapping"""]       )
         UpperCAmelCase							=     images

         return encoded_inputs





      def        _lowercase				(		self						:					List[str]					,       __lowerCamelCase						:					Union[str, Any]					,       __lowerCamelCase						:					List[str]       )    ->   str:






         """simple docstring"""







         UpperCAmelCase							=     []
         for sample_idx in overflow_to_sample_mapping:
            images_with_overflow.append(images[sample_idx]       )

         if len(__lowerCamelCase       ) != len(__lowerCamelCase       ):
            raise ValueError(
                """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"""
                F""" {len(__lowerCamelCase       )} and {len(__lowerCamelCase       )}"""       )

         return images_with_overflow





      def        _lowercase				(		self						:					Dict					,       *__lowerCamelCase						:					Tuple					,       **__lowerCamelCase						:					Dict       )    ->   Optional[int]:






         """simple docstring"""







         return self.tokenizer.batch_decode(*__lowerCamelCase					,       **__lowerCamelCase       )





      def        _lowercase				(		self						:					Optional[int]					,       *__lowerCamelCase						:					Any					,       **__lowerCamelCase						:					Dict       )    ->   List[str]:






         """simple docstring"""







         return self.tokenizer.decode(*__lowerCamelCase					,       **__lowerCamelCase       )





      @property
      def        _lowercase				(		self						:					Union[str, Any]       )    ->   Optional[Any]:






         """simple docstring"""







         return ["input_ids", "bbox", "attention_mask", "image"]





      @property
      def        _lowercase				(		self						:					Optional[int]       )    ->   str:






         """simple docstring"""







         warnings.warn(
             """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""					,       __lowerCamelCase					,       )
         return self.image_processor_class





      @property
      def        _lowercase				(		self						:					str       )    ->   Dict:






         """simple docstring"""







         warnings.warn(
             """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""					,       __lowerCamelCase					,       )
         return self.image_processor







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__a     =			logging.get_logger(__name__)

__a     =			{"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""}






class   __lowercase				(  __snake_case  ):
      UpperCamelCase								=       '''ctrl'''
      UpperCamelCase								=       ['''past_key_values''']
      UpperCamelCase								=       {
          '''max_position_embeddings''': '''n_positions''',
          '''hidden_size''': '''n_embd''',
          '''num_attention_heads''': '''n_head''',
          '''num_hidden_layers''': '''n_layer''',
      }





      def __init__(		self						:					str					,       __lowerCamelCase						:					Optional[int]=2_4_6_5_3_4					,       __lowerCamelCase						:					Union[str, Any]=2_5_6					,       __lowerCamelCase						:					int=1_2_8_0					,       __lowerCamelCase						:					Optional[Any]=8_1_9_2					,       __lowerCamelCase						:					List[str]=4_8					,       __lowerCamelCase						:					Dict=1_6					,       __lowerCamelCase						:					Union[str, Any]=0.1					,       __lowerCamelCase						:					Union[str, Any]=0.1					,       __lowerCamelCase						:					Union[str, Any]=1e-6					,       __lowerCamelCase						:					str=0.02					,       __lowerCamelCase						:					Union[str, Any]=True					,       **__lowerCamelCase						:					List[str]					,       )    ->   Optional[Any]:






         """simple docstring"""







         UpperCAmelCase							=     vocab_size
         UpperCAmelCase							=     n_positions
         UpperCAmelCase							=     n_embd
         UpperCAmelCase							=     n_layer
         UpperCAmelCase							=     n_head
         UpperCAmelCase							=     dff
         UpperCAmelCase							=     resid_pdrop
         UpperCAmelCase							=     embd_pdrop
         UpperCAmelCase							=     layer_norm_epsilon
         UpperCAmelCase							=     initializer_range

         UpperCAmelCase							=     use_cache

         super().__init__(**__lowerCamelCase       )



