


import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
						    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
						    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
						    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
						    LayoutLMvaConfig,
						    LayoutLMvaForQuestionAnswering,
						    LayoutLMvaForSequenceClassification,
						    LayoutLMvaForTokenClassification,
						    LayoutLMvaModel,
						)
						from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
						from PIL import Image

						from transformers import LayoutLMvaImageProcessor







class  snake_case_     :
					def __init__(   self     :str    ,__snake_case     :int    ,__snake_case     :Tuple=2    ,__snake_case     :List[Any]=3    ,__snake_case     :Union[str, Any]=4    ,__snake_case     :Dict=2    ,__snake_case     :List[Any]=7    ,__snake_case     :int=True    ,__snake_case     :Union[str, Any]=True    ,__snake_case     :Union[str, Any]=True    ,__snake_case     :Optional[int]=True    ,__snake_case     :str=99    ,__snake_case     :Any=36    ,__snake_case     :Optional[int]=3    ,__snake_case     :Union[str, Any]=4    ,__snake_case     :Any=37    ,__snake_case     :Any="gelu"    ,__snake_case     :Dict=0.1    ,__snake_case     :List[str]=0.1    ,__snake_case     :Optional[Any]=5_12    ,__snake_case     :List[Any]=16    ,__snake_case     :int=2    ,__snake_case     :Optional[int]=0.02    ,__snake_case     :Union[str, Any]=6    ,__snake_case     :Dict=6    ,__snake_case     :List[Any]=3    ,__snake_case     :Dict=4    ,__snake_case     :Dict=None    ,__snake_case     :Optional[Any]=10_00    ,)      ->					Optional[Any]:
												a__    =  parent
												a__    =  batch_size
												a__    =  num_channels
												a__    =  image_size
												a__    =  patch_size
												a__    =  text_seq_length
												a__    =  is_training
												a__    =  use_input_mask
												a__    =  use_token_type_ids
												a__    =  use_labels
												a__    =  vocab_size
												a__    =  hidden_size
												a__    =  num_hidden_layers
												a__    =  num_attention_heads
												a__    =  intermediate_size
												a__    =  hidden_act
												a__    =  hidden_dropout_prob
												a__    =  attention_probs_dropout_prob
												a__    =  max_position_embeddings
												a__    =  type_vocab_size
												a__    =  type_sequence_label_size
												a__    =  initializer_range
												a__    =  coordinate_size
												a__    =  shape_size
												a__    =  num_labels
												a__    =  num_choices
												a__    =  scope
												a__    =  range_bbox

												# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
												a__    =  text_seq_length
												a__    =  (image_size // patch_size) ** 2 + 1
												a__    =  self.text_seq_length + self.image_seq_length
					def 				lowerCamelCase__(   self     :str   )      ->					List[str]:
												a__    =  ids_tensor([self.batch_size, self.text_seq_length]    ,self.vocab_size   )

												a__    =  ids_tensor([self.batch_size, self.text_seq_length, 4]    ,self.range_bbox   )
												# Ensure that bbox is legal
												for i in range(bbox.shape[0]   ):
																			for j in range(bbox.shape[1]   ):
																										if bbox[i, j, 3] < bbox[i, j, 1]:
																																	a__    =  bbox[i, j, 3]
																																	a__    =  bbox[i, j, 1]
																																	a__    =  t
																										if bbox[i, j, 2] < bbox[i, j, 0]:
																																	a__    =  bbox[i, j, 2]
																																	a__    =  bbox[i, j, 0]
																																	a__    =  t

												a__    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

												a__    =  None
												if self.use_input_mask:
																			a__    =  random_attention_mask([self.batch_size, self.text_seq_length]   )

												a__    =  None
												if self.use_token_type_ids:
																			a__    =  ids_tensor([self.batch_size, self.text_seq_length]    ,self.type_vocab_size   )

												a__    =  None
												a__    =  None
												if self.use_labels:
																			a__    =  ids_tensor([self.batch_size]    ,self.type_sequence_label_size   )
																			a__    =  ids_tensor([self.batch_size, self.text_seq_length]    ,self.num_labels   )

												a__    =  LayoutLMvaConfig(
												    vocab_size=self.vocab_size    ,hidden_size=self.hidden_size    ,num_hidden_layers=self.num_hidden_layers    ,num_attention_heads=self.num_attention_heads    ,intermediate_size=self.intermediate_size    ,hidden_act=self.hidden_act    ,hidden_dropout_prob=self.hidden_dropout_prob    ,attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,max_position_embeddings=self.max_position_embeddings    ,type_vocab_size=self.type_vocab_size    ,initializer_range=self.initializer_range    ,coordinate_size=self.coordinate_size    ,shape_size=self.shape_size    ,input_size=self.image_size    ,patch_size=self.patch_size    ,)

												return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
					def 				lowerCamelCase__(   self     :Tuple    ,__snake_case     :int    ,__snake_case     :str    ,__snake_case     :str    ,__snake_case     :Dict    ,__snake_case     :int    ,__snake_case     :Union[str, Any]    ,__snake_case     :int    ,__snake_case     :List[Any]   )      ->					Union[str, Any]:
												a__    =  LayoutLMvaModel(config=__snake_case   )
												model.to(__snake_case   )
												model.eval()

												# text + image
												a__    =  model(__snake_case    ,pixel_values=__snake_case   )
												a__    =  model(
												    __snake_case    ,bbox=__snake_case    ,pixel_values=__snake_case    ,attention_mask=__snake_case    ,token_type_ids=__snake_case   )
												a__    =  model(__snake_case    ,bbox=__snake_case    ,pixel_values=__snake_case    ,token_type_ids=__snake_case   )
												a__    =  model(__snake_case    ,bbox=__snake_case    ,pixel_values=__snake_case   )

												self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)   )

												# text only
												a__    =  model(__snake_case   )
												self.parent.assertEqual(
												    result.last_hidden_state.shape    ,(self.batch_size, self.text_seq_length, self.hidden_size)   )

												# image only
												a__    =  model(pixel_values=__snake_case   )
												self.parent.assertEqual(
												    result.last_hidden_state.shape    ,(self.batch_size, self.image_seq_length, self.hidden_size)   )
					def 				lowerCamelCase__(   self     :Tuple    ,__snake_case     :Union[str, Any]    ,__snake_case     :Optional[int]    ,__snake_case     :Optional[Any]    ,__snake_case     :str    ,__snake_case     :Optional[Any]    ,__snake_case     :List[Any]    ,__snake_case     :List[str]    ,__snake_case     :int   )      ->					List[Any]:
												a__    =  self.num_labels
												a__    =  LayoutLMvaForSequenceClassification(__snake_case   )
												model.to(__snake_case   )
												model.eval()
												a__    =  model(
												    __snake_case    ,bbox=__snake_case    ,pixel_values=__snake_case    ,attention_mask=__snake_case    ,token_type_ids=__snake_case    ,labels=__snake_case    ,)
												self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)   )
					def 				lowerCamelCase__(   self     :Dict    ,__snake_case     :int    ,__snake_case     :Optional[Any]    ,__snake_case     :List[str]    ,__snake_case     :Tuple    ,__snake_case     :List[Any]    ,__snake_case     :List[Any]    ,__snake_case     :Optional[Any]    ,__snake_case     :Dict   )      ->					Optional[Any]:
												a__    =  self.num_labels
												a__    =  LayoutLMvaForTokenClassification(config=__snake_case   )
												model.to(__snake_case   )
												model.eval()
												a__    =  model(
												    __snake_case    ,bbox=__snake_case    ,pixel_values=__snake_case    ,attention_mask=__snake_case    ,token_type_ids=__snake_case    ,labels=__snake_case    ,)
												self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.text_seq_length, self.num_labels)   )
					def 				lowerCamelCase__(   self     :List[str]    ,__snake_case     :Any    ,__snake_case     :Optional[Any]    ,__snake_case     :str    ,__snake_case     :Tuple    ,__snake_case     :Tuple    ,__snake_case     :Optional[int]    ,__snake_case     :Union[str, Any]    ,__snake_case     :Union[str, Any]   )      ->					Dict:
												a__    =  LayoutLMvaForQuestionAnswering(config=__snake_case   )
												model.to(__snake_case   )
												model.eval()
												a__    =  model(
												    __snake_case    ,bbox=__snake_case    ,pixel_values=__snake_case    ,attention_mask=__snake_case    ,token_type_ids=__snake_case    ,start_positions=__snake_case    ,end_positions=__snake_case    ,)
												self.parent.assertEqual(result.start_logits.shape    ,(self.batch_size, self.seq_length)   )
												self.parent.assertEqual(result.end_logits.shape    ,(self.batch_size, self.seq_length)   )



					def 				lowerCamelCase__(   self     :List[Any]   )      ->					Union[str, Any]:
												a__    =  self.prepare_config_and_inputs()
												(
												    (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      
												)    =  config_and_inputs
												a__    =  {
												    'input_ids': input_ids,
												    'bbox': bbox,
												    'pixel_values': pixel_values,
												    'token_type_ids': token_type_ids,
												    'attention_mask': input_mask,
												}
												return config, inputs_dict







@require_torch
class  snake_case_     (lowerCamelCase_			,		lowerCamelCase_			,		unittest.TestCase   ):
					UpperCAmelCase__      :					Optional[Any]					   =    False
					UpperCAmelCase__      :					Union[str, Any]					   =    False
					UpperCAmelCase__      :					Tuple					   =    False

					UpperCAmelCase__      :					List[str]					   =    (
					    (
					        LayoutLMvaModel,
					        LayoutLMvaForSequenceClassification,
					        LayoutLMvaForTokenClassification,
					        LayoutLMvaForQuestionAnswering,
					    )
					    if is_torch_available()
					    else ()
					)
					UpperCAmelCase__      :					List[Any]					   =    (
					    {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel}
					    if is_torch_available()
					    else {}
					)
					def 				lowerCamelCase__(   self     :List[str]    ,__snake_case     :int    ,__snake_case     :List[str]    ,__snake_case     :int    ,__snake_case     :Union[str, Any]    ,__snake_case     :int   )      ->					Tuple:
												# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
												# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
												# the sequence dimension of the text embedding only.
												# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
												return True
					def 				lowerCamelCase__(   self     :List[str]   )      ->					List[Any]:
												a__    =  LayoutLMvaModelTester(self   )
												a__    =  ConfigTester(self    ,config_class=__snake_case    ,hidden_size=37   )
					def 				lowerCamelCase__(   self     :str    ,__snake_case     :Union[str, Any]    ,__snake_case     :Dict    ,__snake_case     :Union[str, Any]=False   )      ->					Tuple:
												a__    =  copy.deepcopy(__snake_case   )
												if model_class in get_values(__snake_case   ):
																			a__    =  {
																			    k: v.unsqueeze(1   ).expand(-1    ,self.model_tester.num_choices    ,-1   ).contiguous()
																			    if isinstance(__snake_case    ,torch.Tensor   ) and v.ndim > 1
																			    else v
																			    for k, v in inputs_dict.items()
																			}
												if return_labels:
																			if model_class in get_values(__snake_case   ):
																										a__    =  torch.ones(self.model_tester.batch_size    ,dtype=torch.long    ,device=__snake_case   )
																			elif model_class in get_values(__snake_case   ):
																										a__    =  torch.zeros(
																										    self.model_tester.batch_size    ,dtype=torch.long    ,device=__snake_case   )
																										a__    =  torch.zeros(
																										    self.model_tester.batch_size    ,dtype=torch.long    ,device=__snake_case   )
																			elif model_class in [
																			    *get_values(__snake_case   ),
																			]:
																										a__    =  torch.zeros(
																										    self.model_tester.batch_size    ,dtype=torch.long    ,device=__snake_case   )
																			elif model_class in [
																			    *get_values(__snake_case   ),
																			]:
																										a__    =  torch.zeros(
																										    (self.model_tester.batch_size, self.model_tester.text_seq_length)    ,dtype=torch.long    ,device=__snake_case    ,)

												return inputs_dict
					def 				lowerCamelCase__(   self     :str   )      ->					str:
												self.config_tester.run_common_tests()
					def 				lowerCamelCase__(   self     :List[str]   )      ->					Union[str, Any]:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__snake_case   )
					def 				lowerCamelCase__(   self     :str   )      ->					Optional[Any]:
												a__    =  self.model_tester.prepare_config_and_inputs()
												for type in ["absolute", "relative_key", "relative_key_query"]:
																			a__    =  type
																			self.model_tester.create_and_check_model(*__snake_case   )
					def 				lowerCamelCase__(   self     :List[str]   )      ->					str:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*__snake_case   )
					def 				lowerCamelCase__(   self     :Any   )      ->					Dict:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_token_classification(*__snake_case   )
					def 				lowerCamelCase__(   self     :Any   )      ->					Union[str, Any]:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*__snake_case   )



					@slow
					def 				lowerCamelCase__(   self     :Optional[int]   )      ->					int:
												for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			a__    =  LayoutLMvaModel.from_pretrained(__snake_case   )
																			self.assertIsNotNone(__snake_case   )






def 							__lowercase     (				):
							a__    =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
							return image







@require_torch
class  snake_case_     (unittest.TestCase   ):
					@cached_property
					def 				lowerCamelCase__(   self     :Dict   )      ->					Dict:
												return LayoutLMvaImageProcessor(apply_ocr=__snake_case   ) if is_vision_available() else None



					@slow
					def 				lowerCamelCase__(   self     :List[Any]   )      ->					Optional[int]:
												a__    =  LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'   ).to(__snake_case   )

												a__    =  self.default_image_processor
												a__    =  prepare_img()
												a__    =  image_processor(images=__snake_case    ,return_tensors='pt'   ).pixel_values.to(__snake_case   )

												a__    =  torch.tensor([[1, 2]]   )
												a__    =  torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]   ).unsqueeze(0   )

												# forward pass
												a__    =  model(
												    input_ids=input_ids.to(__snake_case   )    ,bbox=bbox.to(__snake_case   )    ,pixel_values=pixel_values.to(__snake_case   )    ,)

												# verify the logits
												a__    =  torch.Size((1, 1_99, 7_68)   )
												self.assertEqual(outputs.last_hidden_state.shape    ,__snake_case   )

												a__    =  torch.tensor(
												    [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]]   ).to(__snake_case   )

												self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]    ,__snake_case    ,atol=1E-4   )   )








from sklearn.metrics import fa_score

import datasets


snake_case							: Optional[int]      =   '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


snake_case							: List[Any]      =   '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

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

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


snake_case							: Union[str, Any]      =   '''
@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  snake_case_     (datasets.Metric   ):
					def 				lowerCamelCase__(   self     :Any   )      ->					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.f1_score.html']    ,)



					def 				lowerCamelCase__(   self     :Dict    ,__snake_case     :str    ,__snake_case     :str    ,__snake_case     :Dict=None    ,__snake_case     :str=1    ,__snake_case     :Optional[int]="binary"    ,__snake_case     :Union[str, Any]=None   )      ->					Tuple:
												a__    =  fa_score(
												    __snake_case    ,__snake_case    ,labels=__snake_case    ,pos_label=__snake_case    ,average=__snake_case    ,sample_weight=__snake_case   )
												return {"f1": float(__snake_case   ) if score.size == 1 else score}




