




"""simple docstring"""




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__							(       UpperCAmelCase__				):






				'''simple docstring'''
				__UpperCamelCase			  =						["image_processor", "tokenizer"]
				__UpperCamelCase			  =						"LayoutLMv2ImageProcessor"
				__UpperCamelCase			  =						("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")





				def __init__(       self		, _a=None		, _a=None		, **_a ):





							"""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."""		, _a		, )
										lowerCamelCase			      =					kwargs.pop("""feature_extractor""" )

							lowerCamelCase			      =					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__(_a		, _a )





				def __call__(       self		, _a		, _a = None		, _a = None		, _a = None		, _a = None		, _a = True		, _a = False		, _a = None		, _a = None		, _a = 0		, _a = None		, _a = None		, _a = None		, _a = False		, _a = False		, _a = False		, _a = False		, _a = True		, _a = None		, **_a		, ):





							"""simple docstring"""
							# 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
							lowerCamelCase			      =					self.image_processor(images=_a		, return_tensors=_a )

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

							lowerCamelCase			      =					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=_a		, add_special_tokens=_a		, padding=_a		, truncation=_a		, max_length=_a		, stride=_a		, pad_to_multiple_of=_a		, return_token_type_ids=_a		, return_attention_mask=_a		, return_overflowing_tokens=_a		, return_special_tokens_mask=_a		, return_offsets_mapping=_a		, return_length=_a		, verbose=_a		, return_tensors=_a		, **_a		, )

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

							return encoded_inputs





				def    _lowerCAmelCase				(       self		, _a		, _a ):





							"""simple docstring"""
							# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
							lowerCamelCase			      =					[]
							for sample_idx in overflow_to_sample_mapping:
										images_with_overflow.append(images[sample_idx] )

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

							return images_with_overflow





				def    _lowerCAmelCase				(       self		, *_a		, **_a ):





							"""simple docstring"""
							return self.tokenizer.batch_decode(*_a		, **_a )





				def    _lowerCAmelCase				(       self		, *_a		, **_a ):





							"""simple docstring"""
							return self.tokenizer.decode(*_a		, **_a )





				@property
				def    _lowerCAmelCase				(       self ):





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





				@property
				def    _lowerCAmelCase				(       self ):





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





				@property
				def    _lowerCAmelCase				(       self ):





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









"""simple docstring"""




import functools
import operator

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


lowerCAmelCase							:			int     							=							logging.get_logger(__name__)

lowerCAmelCase							:			List[str]     							=							{
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}






class     __magic_name__							(       UpperCAmelCase__				):






				'''simple docstring'''
				__UpperCamelCase			  =						"sew-d"





				def __init__(       self		, _a=32		, _a=768		, _a=12		, _a=12		, _a=3_072		, _a=2		, _a=512		, _a=256		, _a=True		, _a=True		, _a=("p2c", "c2p")		, _a="layer_norm"		, _a="gelu_python"		, _a=0.1		, _a=0.1		, _a=0.1		, _a=0.0		, _a=0.1		, _a=0.02		, _a=1e-7		, _a=1e-5		, _a="group"		, _a="gelu"		, _a=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)		, _a=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)		, _a=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)		, _a=False		, _a=128		, _a=16		, _a=True		, _a=0.05		, _a=10		, _a=2		, _a=0.0		, _a=10		, _a=0		, _a="mean"		, _a=False		, _a=False		, _a=256		, _a=0		, _a=1		, _a=2		, **_a		, ):





							"""simple docstring"""
							super().__init__(**_a		, pad_token_id=_a		, bos_token_id=_a		, eos_token_id=_a )
							lowerCamelCase			      =					hidden_size
							lowerCamelCase			      =					feat_extract_norm
							lowerCamelCase			      =					feat_extract_activation
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					conv_bias
							lowerCamelCase			      =					num_conv_pos_embeddings
							lowerCamelCase			      =					num_conv_pos_embedding_groups
							lowerCamelCase			      =					len(self.conv_dim )
							lowerCamelCase			      =					num_hidden_layers
							lowerCamelCase			      =					intermediate_size
							lowerCamelCase			      =					squeeze_factor
							lowerCamelCase			      =					max_position_embeddings
							lowerCamelCase			      =					position_buckets
							lowerCamelCase			      =					share_att_key
							lowerCamelCase			      =					relative_attention
							lowerCamelCase			      =					norm_rel_ebd
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					hidden_act
							lowerCamelCase			      =					num_attention_heads
							lowerCamelCase			      =					hidden_dropout
							lowerCamelCase			      =					attention_dropout
							lowerCamelCase			      =					activation_dropout
							lowerCamelCase			      =					feat_proj_dropout
							lowerCamelCase			      =					final_dropout
							lowerCamelCase			      =					layer_norm_eps
							lowerCamelCase			      =					feature_layer_norm_eps
							lowerCamelCase			      =					initializer_range
							lowerCamelCase			      =					vocab_size

							if (
							    (len(self.conv_stride ) != self.num_feat_extract_layers)
							    or (len(self.conv_kernel ) != self.num_feat_extract_layers)
							    or (len(self.conv_dim ) != self.num_feat_extract_layers)
							):
										raise ValueError(
										    """Configuration for convolutional layers is incorrect."""
										    """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
										    f'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'
										    f'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' )

							# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
							lowerCamelCase			      =					apply_spec_augment
							lowerCamelCase			      =					mask_time_prob
							lowerCamelCase			      =					mask_time_length
							lowerCamelCase			      =					mask_time_min_masks
							lowerCamelCase			      =					mask_feature_prob
							lowerCamelCase			      =					mask_feature_length
							lowerCamelCase			      =					mask_feature_min_masks

							# ctc loss
							lowerCamelCase			      =					ctc_loss_reduction
							lowerCamelCase			      =					ctc_zero_infinity

							# sequence classification
							lowerCamelCase			      =					use_weighted_layer_sum
							lowerCamelCase			      =					classifier_proj_size





				@property
				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							return functools.reduce(operator.mul		, self.conv_stride		, 1 )



