



'''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(							UpperCamelCase__      ):
			__snake_case  :		str		=      ["""image_processor""", """tokenizer"""]
			__snake_case  :		Any		=      """LayoutLMv2ImageProcessor"""
			__snake_case  :		Any		=      ("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")






			def __init__(   self  :							Dict      ,       SCREAMING_SNAKE_CASE  :							Dict=None      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]=None      ,       **SCREAMING_SNAKE_CASE  :							str	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:int										=      None
					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      ,       )
							SCREAMING_SNAKE_CASE_						:Dict										=      kwargs.pop('feature_extractor'	)

					SCREAMING_SNAKE_CASE_						: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  :							Optional[int]      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							List[str] = None      ,       SCREAMING_SNAKE_CASE  :							Tuple = None      ,       SCREAMING_SNAKE_CASE  :							int = None      ,       SCREAMING_SNAKE_CASE  :							Any = None      ,       SCREAMING_SNAKE_CASE  :							int = True      ,       SCREAMING_SNAKE_CASE  :							Any = False      ,       SCREAMING_SNAKE_CASE  :							Optional[int] = False      ,       SCREAMING_SNAKE_CASE  :							Dict = None      ,       SCREAMING_SNAKE_CASE  :							Tuple = 0      ,       SCREAMING_SNAKE_CASE  :							Dict = None      ,       SCREAMING_SNAKE_CASE  :							Optional[Any] = None      ,       SCREAMING_SNAKE_CASE  :							List[str] = None      ,       SCREAMING_SNAKE_CASE  :							Dict = False      ,       SCREAMING_SNAKE_CASE  :							Optional[int] = False      ,       SCREAMING_SNAKE_CASE  :							Optional[Any] = False      ,       SCREAMING_SNAKE_CASE  :							Tuple = False      ,       SCREAMING_SNAKE_CASE  :							str = True      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any] = None      ,       **SCREAMING_SNAKE_CASE  :							List[Any]      ,       ):




					"""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
					SCREAMING_SNAKE_CASE_						: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	):
									SCREAMING_SNAKE_CASE_						:List[Any]										=      [text]  # add batch dimension (as the image processor always adds a batch dimension)
							SCREAMING_SNAKE_CASE_						:str										=      features['words']

					SCREAMING_SNAKE_CASE_						:Optional[int]										=      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
					SCREAMING_SNAKE_CASE_						:int										=      features.pop('pixel_values'	)
					if return_overflowing_tokens is True:
							SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      self.get_overflowing_images(SCREAMING_SNAKE_CASE      ,       encoded_inputs['overflow_to_sample_mapping']	)
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      images

					return encoded_inputs






			def 				_lowercase	(   self  :							int      ,       SCREAMING_SNAKE_CASE  :							Any      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Any										=      []
					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 				_lowercase	(   self  :							Optional[Any]      ,       *SCREAMING_SNAKE_CASE  :							List[str]      ,       **SCREAMING_SNAKE_CASE  :							List[str]	):




					"""simple docstring"""







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






			def 				_lowercase	(   self  :							str      ,       *SCREAMING_SNAKE_CASE  :							Union[str, Any]      ,       **SCREAMING_SNAKE_CASE  :							Optional[Any]	):




					"""simple docstring"""







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






			@property
			def 				_lowercase	(   self  :							str	):




					"""simple docstring"""







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






			@property
			def 				_lowercase	(   self  :							Dict	):




					"""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 				_lowercase	(   self  :							Optional[int]	):




					"""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'''



from sklearn.metrics import accuracy_score

import datasets


lowerCAmelCase						:		Optional[Any]						      = '''
Accuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:
Accuracy = (TP + TN) / (TP + TN + FP + FN)
 Where:
TP: True positive
TN: True negative
FP: False positive
FN: False negative
'''


lowerCAmelCase						:		str						      = '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.

Examples:

    Example 1-A simple example
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])
        >>> print(results)
        {\'accuracy\': 0.5}

    Example 2-The same as Example 1, except with `normalize` set to `False`.
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)
        >>> print(results)
        {\'accuracy\': 3.0}

    Example 3-The same as Example 1, except with `sample_weight` set.
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])
        >>> print(results)
        {\'accuracy\': 0.8778625954198473}
'''


lowerCAmelCase						:		int						      = '''
@article{scikit-learn,
  title={Scikit-learn: Machine Learning in {P}ython},
  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  journal={Journal of Machine Learning Research},
  volume={12},
  pages={2825--2830},
  year={2011}
}
'''






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,							_KWARGS_DESCRIPTION			)
class        UpperCAmelCase__						(		datasets.Metric			):



					def 							UpperCAmelCase_			(     self  )  ->      Optional[Any]:
						return datasets.MetricInfo(
						    description=_DESCRIPTION      ,					citation=_CITATION      ,					inputs_description=_KWARGS_DESCRIPTION      ,					features=datasets.Features(
						        {
						            "predictions": datasets.Sequence(datasets.Value("int32"  )  ),
						            "references": datasets.Sequence(datasets.Value("int32"  )  ),
						        }
						        if self.config_name == "multilabel"
						        else {
						            "predictions": datasets.Value("int32"  ),
						            "references": datasets.Value("int32"  ),
						        }  )      ,					reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"]      ,					)



					def 							UpperCAmelCase_			(     self      ,					UpperCamelCase      ,					UpperCamelCase      ,					UpperCamelCase=True      ,					UpperCamelCase=None  )  ->      List[str]:
						return {
						    "accuracy": float(
						        accuracy_score(UpperCamelCase      ,					UpperCamelCase      ,					normalize=UpperCamelCase      ,					sample_weight=UpperCamelCase  )  )
						}