
'''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 			lowerCAmelCase__       (  lowerCamelCase_					):
     lowerCAmelCase_					       =					['''image_processor''', '''tokenizer''']
     lowerCAmelCase_					       =					'''LayoutLMv2ImageProcessor'''
     lowerCAmelCase_					       =					('''LayoutXLMTokenizer''', '''LayoutXLMTokenizerFast''')






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


           """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.'''    ,							__SCREAMING_SNAKE_CASE    ,							)
                 lowercase_     :					Optional[int]													=	kwargs.pop('''feature_extractor'''		)

           lowercase_     :					Dict													=	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__(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		)






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


           """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
           lowercase_     :					Union[str, Any]													=	self.image_processor(images=__SCREAMING_SNAKE_CASE    ,							return_tensors=__SCREAMING_SNAKE_CASE		)

           # second, apply the tokenizer
           if text is not None and self.image_processor.apply_ocr and text_pair is None:
                 if isinstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		):
                       lowercase_     :					Dict													=	[text]  # add batch dimension (as the image processor always adds a batch dimension)
                 lowercase_     :					Optional[int]													=	features['''words''']

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

           # add pixel values
           lowercase_     :					List[Any]													=	features.pop('''pixel_values'''		)
           if return_overflowing_tokens is True:
                 lowercase_     :					Dict													=	self.get_overflowing_images(__SCREAMING_SNAKE_CASE    ,							encoded_inputs['''overflow_to_sample_mapping''']		)
           lowercase_     :					int													=	images

           return encoded_inputs






     def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		):


           """simple docstring"""





           lowercase_     :					Optional[int]													=	[]
           for sample_idx in overflow_to_sample_mapping:
                 images_with_overflow.append(images[sample_idx]		)

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

           return images_with_overflow






     def      _snake_case   (       self    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE		):


           """simple docstring"""





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






     def      _snake_case   (       self    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE		):


           """simple docstring"""





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






     @property
     def      _snake_case   (       self		):


           """simple docstring"""





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






     @property
     def      _snake_case   (       self		):


           """simple docstring"""





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






     @property
     def      _snake_case   (       self		):


           """simple docstring"""





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





'''simple docstring'''







import logging
import os

from .state import PartialState






class 			lowerCAmelCase__       (  logging.LoggerAdapter					):






					@staticmethod
					def      _snake_case   (       __SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_     :					Optional[Any]													=	PartialState()
											return not main_process_only or (main_process_only and state.is_main_process)






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if PartialState._shared_state == {}:
																	raise RuntimeError(
																	    '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.'''		)
											lowercase_     :					Tuple													=	kwargs.pop('''main_process_only'''    ,							__SCREAMING_SNAKE_CASE		)
											lowercase_     :					Optional[int]													=	kwargs.pop('''in_order'''    ,							__SCREAMING_SNAKE_CASE		)

											if self.isEnabledFor(__SCREAMING_SNAKE_CASE		):
																	if self._should_log(__SCREAMING_SNAKE_CASE		):
																							lowercase_						,			lowercase_     :					Optional[Any]													=	self.process(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		)
																							self.logger.log(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE		)

																	elif in_order:
																							lowercase_     :					Optional[Any]													=	PartialState()
																							for i in range(state.num_processes		):
																													if i == state.process_index:
																																			lowercase_						,			lowercase_     :					Optional[int]													=	self.process(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		)
																																			self.logger.log(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE		)
																													state.wait_for_everyone()







def  snake_case_		(    __SCREAMING_SNAKE_CASE :			str				,				__SCREAMING_SNAKE_CASE :			str = None							):



						"""simple docstring"""





						if log_level is None:
												lowercase_     :					Any													=	os.environ.get('''ACCELERATE_LOG_LEVEL'''				,				__SCREAMING_SNAKE_CASE							)
						lowercase_     :					List[str]													=	logging.getLogger(__SCREAMING_SNAKE_CASE							)
						if log_level is not None:
												logger.setLevel(log_level.upper()							)
												logger.root.setLevel(log_level.upper()							)
						return MultiProcessAdapter(__SCREAMING_SNAKE_CASE				,				{}							)



