

from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase__							=			logging.get_logger(__name__)






class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""input_ids""", """attention_mask"""]


 def __init__(    self		:			Union[str, Any]      ,    lowerCAmelCase__		:			str="[PAD]"      ,    lowerCAmelCase__		:			Tuple="[BOS]"      ,    lowerCAmelCase__		:			Optional[Any]="[EOS]"      ,    lowerCAmelCase__		:			Dict="[MASK]"      ,    lowerCAmelCase__		:			int="[CLS]"      ,    lowerCAmelCase__		:			Any="[SEP]"      ,    lowerCAmelCase__		:			Any=2_0_4_8      ,    **lowerCAmelCase__		:			int      ,    )     ->   None:
   UpperCAmelCase          =	AddedToken(lowerCAmelCase__      ,    lstrip=lowerCAmelCase__      ,    rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) else pad_token
   UpperCAmelCase          =	AddedToken(lowerCAmelCase__      ,    lstrip=lowerCAmelCase__      ,    rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) else bos_token
   UpperCAmelCase          =	AddedToken(lowerCAmelCase__      ,    lstrip=lowerCAmelCase__      ,    rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) else eos_token
   UpperCAmelCase          =	AddedToken(lowerCAmelCase__      ,    lstrip=lowerCAmelCase__      ,    rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) else mask_token
   UpperCAmelCase          =	AddedToken(lowerCAmelCase__      ,    lstrip=lowerCAmelCase__      ,    rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) else cls_token
   UpperCAmelCase          =	AddedToken(lowerCAmelCase__      ,    lstrip=lowerCAmelCase__      ,    rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ) else sep_token

   super().__init__(
       pad_token=lowerCAmelCase__      ,    bos_token=lowerCAmelCase__      ,    eos_token=lowerCAmelCase__      ,    mask_token=lowerCAmelCase__      ,    cls_token=lowerCAmelCase__      ,    sep_token=lowerCAmelCase__      ,    model_max_length=lowerCAmelCase__      ,    **lowerCAmelCase__      ,    )

   UpperCAmelCase          =	2**8  # utf is 8 bits

   # define special tokens dict
   UpperCAmelCase          =	{
       self.pad_token: 0,
       self.bos_token: 1,
       self.eos_token: 2,
       self.mask_token: 3,
       self.cls_token: 4,
       self.sep_token: 5,
   }
   UpperCAmelCase          =	len(self.special_tokens_encoder     )
   UpperCAmelCase          =	{v: k for k, v in self.special_tokens_encoder.items()}


 def _UpperCamelCase						(    self		:			int     )     ->   Dict[str, int]:
   UpperCAmelCase          =	self.special_tokens_encoder.copy()
   vocab.update(self.added_tokens_encoder     )
   for i in range(self._utf_vocab_size     ):
     UpperCAmelCase          =	chr(lowerCAmelCase__     )
     UpperCAmelCase          =	i + len(self.special_tokens_encoder     )
   return vocab


 @property
 def _UpperCamelCase						(    self		:			int     )     ->   Dict:
   return self._utf_vocab_size + self._num_special_tokens


 def _UpperCamelCase						(    self		:			Dict      ,    lowerCAmelCase__		:			List[int]      ,    lowerCAmelCase__		:			Optional[List[int]] = None      ,    lowerCAmelCase__		:			bool = False     )     ->   List[int]:
   if already_has_special_tokens:
     return super().get_special_tokens_mask(
         token_ids_a=lowerCAmelCase__      ,    token_ids_a=lowerCAmelCase__      ,    already_has_special_tokens=lowerCAmelCase__     )

   # normal case: some special tokens
   if token_ids_a is None:
     return [1] + [0] * len(lowerCAmelCase__     ) + [1]
   return [1] + ([0] * len(lowerCAmelCase__     )) + [1] + ([0] * len(lowerCAmelCase__     )) + [1]


 def _UpperCamelCase						(    self		:			Optional[int]      ,    lowerCAmelCase__		:			List[int]      ,    lowerCAmelCase__		:			Optional[List[int]] = None     )     ->   List[int]:
   if token_ids_a is None:
     return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
   else:
     return [self.cls_token_id] + token_ids_a + [self.sep_token_id] + token_ids_a + [self.sep_token_id]


 def _UpperCamelCase						(    self		:			List[Any]      ,    lowerCAmelCase__		:			str     )     ->   List[str]:
   UpperCAmelCase          =	[chr(lowerCAmelCase__     ) for i in text.encode("utf-8"     )]
   return tokens


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    lowerCAmelCase__		:			Dict     )     ->   Dict:
   if token in self.special_tokens_encoder:
     UpperCAmelCase          =	self.special_tokens_encoder[token]
   elif token in self.added_tokens_encoder:
     UpperCAmelCase          =	self.added_tokens_encoder[token]
   elif len(lowerCAmelCase__     ) != 1:
     UpperCAmelCase          =	self.unk_token_id
   else:
     UpperCAmelCase          =	ord(lowerCAmelCase__     ) + self._num_special_tokens
   return token_id


 def _UpperCamelCase						(    self		:			Dict      ,    lowerCAmelCase__		:			Any     )     ->   List[str]:
   if index in self.special_tokens_decoder:
     UpperCAmelCase          =	self.special_tokens_decoder[index]
   elif index in self.added_tokens_decoder:
     UpperCAmelCase          =	self.added_tokens_decoder[index]
   else:
     UpperCAmelCase          =	chr(index - self._num_special_tokens     )
   return token


 def _UpperCamelCase						(    self		:			Optional[Any]      ,    lowerCAmelCase__		:			List[Any]     )     ->   Optional[Any]:
   UpperCAmelCase          =	b""
   for token in tokens:
     if token in self.special_tokens_decoder:
       UpperCAmelCase          =	self.special_tokens_decoder[token].encode("utf-8"     )
     elif token in self.added_tokens_decoder:
       UpperCAmelCase          =	self.special_tokens_decoder[token].encode("utf-8"     )
     elif token in self.special_tokens_encoder:
       UpperCAmelCase          =	token.encode("utf-8"     )
     elif token in self.added_tokens_encoder:
       UpperCAmelCase          =	token.encode("utf-8"     )
     else:
       UpperCAmelCase          =	bytes([ord(lowerCAmelCase__     )]     )
     bstring += tok_string
   UpperCAmelCase          =	bstring.decode("utf-8"      ,    errors="replace"     )
   return string


 def _UpperCamelCase						(    self		:			List[Any]      ,    lowerCAmelCase__		:			str      ,    lowerCAmelCase__		:			Optional[str] = None     )     ->   Tuple[str]:
   return ()






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     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""image_processor""", """tokenizer"""]
 UpperCAmelCase				     =    """LayoutLMv2ImageProcessor"""
 UpperCAmelCase				     =    ("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")


 def __init__(    self		:			Any      ,    lowerCAmelCase__		:			Any=None      ,    lowerCAmelCase__		:			Optional[Any]=None      ,    **lowerCAmelCase__		:			int     )     ->   Union[str, Any]:
   UpperCAmelCase          =	None
   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		:			int      ,    lowerCAmelCase__		:			Tuple      ,    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] = False      ,    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__		:			Any      ,    )     ->   BatchEncoding:
   # verify input
   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 _UpperCamelCase						(    self		:			str      ,    lowerCAmelCase__		:			Union[str, Any]      ,    lowerCAmelCase__		:			Union[str, Any]     )     ->   int:
   # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
   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 _UpperCamelCase						(    self		:			Optional[Any]      ,    *lowerCAmelCase__		:			int      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[str]:
   return self.tokenizer.batch_decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    *lowerCAmelCase__		:			Tuple      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[Any]:
   return self.tokenizer.decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 @property
 def _UpperCamelCase						(    self		:			int     )     ->   List[str]:
   return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]


 @property
 def _UpperCamelCase						(    self		:			Dict     )     ->   List[str]:
   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 _UpperCamelCase						(    self		:			List[Any]     )     ->   int:
   warnings.warn(
       "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor



