

import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


snake_case_			  = logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''')

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    np.ndarray	,     SCREAMING_SNAKE_CASE_		:    float	,     SCREAMING_SNAKE_CASE_		:    int = 16_000			):



     '''simple docstring'''





     lowercase__    :   Optional[Any]      =       int(round(sample_rate * max_length			)			)
     if len(SCREAMING_SNAKE_CASE_			) <= sample_length:
          return wav
     lowercase__    :   int      =       randint(0	,     len(SCREAMING_SNAKE_CASE_			) - sample_length - 1			)
     return wav[random_offset : random_offset + sample_length]


@dataclass
class       SCREAMING_SNAKE_CASE__					:
    __lowerCamelCase						:       Optional[str]														=     field(default=__snake_case		,       metadata={"""help""": """Name of a dataset from the datasets package"""}     )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}     )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """A file containing the training audio paths and labels."""}     )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """A file containing the validation audio paths and labels."""}     )
    __lowerCamelCase						:       str														=     field(
        default="""train"""		,       metadata={
            """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
        }		,       )
    __lowerCamelCase						:       str														=     field(
        default="""validation"""		,       metadata={
            """help""": (
                """The name of the training data set split to use (via the datasets library). Defaults to 'validation'"""
            )
        }		,       )
    __lowerCamelCase						:       str														=     field(
        default="""audio"""		,       metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""}		,       )
    __lowerCamelCase						:       str														=     field(
        default="""label"""		,       metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""}     )
    __lowerCamelCase						:       Optional[int]														=     field(
        default=__snake_case		,       metadata={
            """help""": (
                """For debugging purposes or quicker training, truncate the number of training examples to this """
                """value if set."""
            )
        }		,       )
    __lowerCamelCase						:       Optional[int]														=     field(
        default=__snake_case		,       metadata={
            """help""": (
                """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
                """value if set."""
            )
        }		,       )
    __lowerCamelCase						:       float														=     field(
        default=20		,       metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""}		,       )



@dataclass
class       SCREAMING_SNAKE_CASE__					:
    __lowerCamelCase						:       str														=     field(
        default="""facebook/wav2vec2-base"""		,       metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}		,       )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}     )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""}     )
    __lowerCamelCase						:       str														=     field(
        default="""main"""		,       metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}		,       )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """Name or path of preprocessor config."""}     )
    __lowerCamelCase						:       bool														=     field(
        default=__snake_case		,       metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""}     )
    __lowerCamelCase						:       bool														=     field(
        default=__snake_case		,       metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""}     )
    __lowerCamelCase						:       bool														=     field(
        default=__snake_case		,       metadata={
            """help""": (
                """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
                """with private models)."""
            )
        }		,       )
    __lowerCamelCase						:       Optional[bool]														=     field(
        default=__snake_case		,       metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}     )
    __lowerCamelCase						:       bool														=     field(
        default=__snake_case		,       metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}		,       )





    def       snake_case_				(      self):
         if not self.freeze_feature_extractor and self.freeze_feature_encoder:
              warnings.warn(
                  'The argument `--freeze_feature_extractor` is deprecated and '
                  'will be removed in a future version. Use `--freeze_feature_encoder`'
                  'instead. Setting `freeze_feature_encoder==True`.'						,   a						,   )
         if self.freeze_feature_extractor and not self.freeze_feature_encoder:
              raise ValueError(
                  'The argument `--freeze_feature_extractor` is deprecated and '
                  'should not be used in combination with `--freeze_feature_encoder`.'
                  'Only make use of `--freeze_feature_encoder`.')



def 	snake_case__			(    ):



     '''simple docstring'''





     lowercase__    :   List[Any]      =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
     if len(sys.argv			) == 2 and sys.argv[1].endswith('.json'			):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          lowercase__      , lowercase__      , lowercase__    :   List[Any]      =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
     else:
          lowercase__      , lowercase__      , lowercase__    :   Tuple      =       parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('run_audio_classification'	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)

     # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'	,     datefmt='%m/%d/%Y %H:%M:%S'	,     handlers=[logging.StreamHandler(sys.stdout			)]	,     )

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     lowercase__    :   Dict      =       training_args.get_process_log_level()
     logger.setLevel(SCREAMING_SNAKE_CASE_			)
     transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE_			)
     transformers.utils.logging.enable_default_handler()
     transformers.utils.logging.enable_explicit_format()

     # Log on each process the small summary:
     logger.warning(
         f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """
         + f"""distributed training: {bool(training_args.local_rank != -1			)}, 16-bits training: {training_args.fpaa}"""			)
     logger.info(f"""Training/evaluation parameters {training_args}"""			)

     # Set seed before initializing model.
     set_seed(training_args.seed			)

     # Detecting last checkpoint.
     lowercase__    :   List[str]      =       None
     if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
          lowercase__    :   Any      =       get_last_checkpoint(training_args.output_dir			)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir			)			) > 0:
               raise ValueError(
                   f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                   'Use --overwrite_output_dir to train from scratch.'			)
          elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
               logger.info(
                   f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                   'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'			)

    # Initialize our dataset and prepare it for the audio classification task.
     lowercase__    :   Dict      =       DatasetDict()
     lowercase__    :   List[str]      =       load_dataset(
         data_args.dataset_name	,     data_args.dataset_config_name	,     split=data_args.train_split_name	,     use_auth_token=True if model_args.use_auth_token else None	,     )
     lowercase__    :   List[Any]      =       load_dataset(
         data_args.dataset_name	,     data_args.dataset_config_name	,     split=data_args.eval_split_name	,     use_auth_token=True if model_args.use_auth_token else None	,     )

     if data_args.audio_column_name not in raw_datasets["train"].column_names:
          raise ValueError(
              f"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """
              'Make sure to set `--audio_column_name` to the correct audio column - one of '
              f"""{", ".join(raw_datasets["train"].column_names			)}."""			)

     if data_args.label_column_name not in raw_datasets["train"].column_names:
          raise ValueError(
              f"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """
              'Make sure to set `--label_column_name` to the correct text column - one of '
              f"""{", ".join(raw_datasets["train"].column_names			)}."""			)

     # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
     # transformer outputs in the classifier, but it doesn't always lead to better accuracy
     lowercase__    :   Tuple      =       AutoFeatureExtractor.from_pretrained(
         model_args.feature_extractor_name or model_args.model_name_or_path	,     return_attention_mask=model_args.attention_mask	,     cache_dir=model_args.cache_dir	,     revision=model_args.model_revision	,     use_auth_token=True if model_args.use_auth_token else None	,     )

     # `datasets` takes care of automatically loading and resampling the audio,
     # so we just need to set the correct target sampling rate.
     lowercase__    :   Dict      =       raw_datasets.cast_column(
         data_args.audio_column_name	,     datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate			)			)

     lowercase__    :   Optional[int]      =       feature_extractor.model_input_names[0]

     def train_transforms(SCREAMING_SNAKE_CASE_		:    Optional[Any]			):
          lowercase__    :   Optional[Any]      =       []
          for audio in batch[data_args.audio_column_name]:
               lowercase__    :   str      =       random_subsample(
                   audio['array']	,     max_length=data_args.max_length_seconds	,     sample_rate=feature_extractor.sampling_rate			)
               subsampled_wavs.append(SCREAMING_SNAKE_CASE_			)
          lowercase__    :   List[str]      =       feature_extractor(SCREAMING_SNAKE_CASE_	,     sampling_rate=feature_extractor.sampling_rate			)
          lowercase__    :   str      =       {model_input_name: inputs.get(SCREAMING_SNAKE_CASE_			)}
          lowercase__    :   Optional[Any]      =       list(batch[data_args.label_column_name]			)

          return output_batch

     def val_transforms(SCREAMING_SNAKE_CASE_		:    int			):
          lowercase__    :   List[Any]      =       [audio['array'] for audio in batch[data_args.audio_column_name]]
          lowercase__    :   Any      =       feature_extractor(SCREAMING_SNAKE_CASE_	,     sampling_rate=feature_extractor.sampling_rate			)
          lowercase__    :   str      =       {model_input_name: inputs.get(SCREAMING_SNAKE_CASE_			)}
          lowercase__    :   Union[str, Any]      =       list(batch[data_args.label_column_name]			)

          return output_batch

     # Prepare label mappings.
     # We'll include these in the model's config to get human readable labels in the Inference API.
     lowercase__    :   List[Any]      =       raw_datasets['train'].features[data_args.label_column_name].names
     lowercase__      , lowercase__    :   Any      =       {}, {}
     for i, label in enumerate(SCREAMING_SNAKE_CASE_			):
          lowercase__    :   Optional[Any]      =       str(SCREAMING_SNAKE_CASE_			)
          lowercase__    :   Union[str, Any]      =       label

     # Load the accuracy metric from the datasets package
     lowercase__    :   Dict      =       evaluate.load('accuracy'			)

     # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
     # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
     def compute_metrics(SCREAMING_SNAKE_CASE_		:    Tuple			):
          lowercase__    :   Any      =       np.argmax(eval_pred.predictions	,     axis=1			)
          return metric.compute(predictions=SCREAMING_SNAKE_CASE_	,     references=eval_pred.label_ids			)

     lowercase__    :   List[Any]      =       AutoConfig.from_pretrained(
         model_args.config_name or model_args.model_name_or_path	,     num_labels=len(SCREAMING_SNAKE_CASE_			)	,     labelaid=SCREAMING_SNAKE_CASE_	,     idalabel=SCREAMING_SNAKE_CASE_	,     finetuning_task='audio-classification'	,     cache_dir=model_args.cache_dir	,     revision=model_args.model_revision	,     use_auth_token=True if model_args.use_auth_token else None	,     )
     lowercase__    :   Dict      =       AutoModelForAudioClassification.from_pretrained(
         model_args.model_name_or_path	,     from_tf=bool('.ckpt' in model_args.model_name_or_path			)	,     config=SCREAMING_SNAKE_CASE_	,     cache_dir=model_args.cache_dir	,     revision=model_args.model_revision	,     use_auth_token=True if model_args.use_auth_token else None	,     ignore_mismatched_sizes=model_args.ignore_mismatched_sizes	,     )

     # freeze the convolutional waveform encoder
     if model_args.freeze_feature_encoder:
          model.freeze_feature_encoder()

     if training_args.do_train:
          if data_args.max_train_samples is not None:
               lowercase__    :   Optional[int]      =       (
                   raw_datasets['train'].shuffle(seed=training_args.seed			).select(range(data_args.max_train_samples			)			)
               )
          # Set the training transforms
          raw_datasets["train"].set_transform(SCREAMING_SNAKE_CASE_	,     output_all_columns=SCREAMING_SNAKE_CASE_			)

     if training_args.do_eval:
          if data_args.max_eval_samples is not None:
               lowercase__    :   str      =       (
                   raw_datasets['eval'].shuffle(seed=training_args.seed			).select(range(data_args.max_eval_samples			)			)
               )
          # Set the validation transforms
          raw_datasets["eval"].set_transform(SCREAMING_SNAKE_CASE_	,     output_all_columns=SCREAMING_SNAKE_CASE_			)

     # Initialize our trainer
     lowercase__    :   Dict      =       Trainer(
         model=SCREAMING_SNAKE_CASE_	,     args=SCREAMING_SNAKE_CASE_	,     train_dataset=raw_datasets['train'] if training_args.do_train else None	,     eval_dataset=raw_datasets['eval'] if training_args.do_eval else None	,     compute_metrics=SCREAMING_SNAKE_CASE_	,     tokenizer=SCREAMING_SNAKE_CASE_	,     )

     # Training
     if training_args.do_train:
          lowercase__    :   Optional[Any]      =       None
          if training_args.resume_from_checkpoint is not None:
               lowercase__    :   List[Any]      =       training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               lowercase__    :   Optional[int]      =       last_checkpoint
          lowercase__    :   int      =       trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_			)
          trainer.save_model()
          trainer.log_metrics('train'	,     train_result.metrics			)
          trainer.save_metrics('train'	,     train_result.metrics			)
          trainer.save_state()

     # Evaluation
     if training_args.do_eval:
          lowercase__    :   int      =       trainer.evaluate()
          trainer.log_metrics('eval'	,     SCREAMING_SNAKE_CASE_			)
          trainer.save_metrics('eval'	,     SCREAMING_SNAKE_CASE_			)

     # Write model card and (optionally) push to hub
     lowercase__    :   str      =       {
         'finetuned_from': model_args.model_name_or_path,
         'tasks': 'audio-classification',
         'dataset': data_args.dataset_name,
         'tags': ['audio-classification'],
     }
     if training_args.push_to_hub:
          trainer.push_to_hub(**SCREAMING_SNAKE_CASE_			)
     else:
          trainer.create_model_card(**SCREAMING_SNAKE_CASE_			)


if __name__ == "__main__":
       main()




from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers import (
           TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
           TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
           TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
           TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
           TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
           LayoutLMvaConfig,
           TFLayoutLMvaForQuestionAnswering,
           TFLayoutLMvaForSequenceClassification,
           TFLayoutLMvaForTokenClassification,
           TFLayoutLMvaModel,
       )

if is_vision_available():
       from PIL import Image

       from transformers import LayoutLMvaImageProcessor


class       SCREAMING_SNAKE_CASE__					:





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

         # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
         lowercase__    :   Optional[int]      =       text_seq_length
         lowercase__    :   Optional[int]      =       (image_size // patch_size) ** 2 + 1
         lowercase__    :   str      =       self.text_seq_length + self.image_seq_length





    def       snake_case_				(      self):
         lowercase__    :   Dict      =       ids_tensor([self.batch_size, self.text_seq_length]						,   self.vocab_size)

         lowercase__    :   List[Any]      =       ids_tensor([self.batch_size, self.text_seq_length, 4]						,   self.range_bbox)
         lowercase__    :   str      =       bbox.numpy()
         # 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]:
                        lowercase__    :   Optional[Any]      =       bbox[i, j, 3]
                        lowercase__    :   List[Any]      =       bbox[i, j, 1]
                        lowercase__    :   List[str]      =       tmp_coordinate
                   if bbox[i, j, 2] < bbox[i, j, 0]:
                        lowercase__    :   int      =       bbox[i, j, 2]
                        lowercase__    :   List[Any]      =       bbox[i, j, 0]
                        lowercase__    :   Optional[Any]      =       tmp_coordinate
         lowercase__    :   Dict      =       tf.constant(a)

         lowercase__    :   Dict      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

         lowercase__    :   Optional[Any]      =       None
         if self.use_input_mask:
              lowercase__    :   str      =       random_attention_mask([self.batch_size, self.text_seq_length])

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

         lowercase__    :   List[Any]      =       None
         lowercase__    :   Optional[int]      =       None
         if self.use_labels:
              lowercase__    :   Tuple      =       ids_tensor([self.batch_size]						,   self.type_sequence_label_size)
              lowercase__    :   Union[str, Any]      =       ids_tensor([self.batch_size, self.text_seq_length]						,   self.num_labels)

         lowercase__    :   List[str]      =       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       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a						,   a):
         lowercase__    :   str      =       TFLayoutLMvaModel(config=a)

         # text + image
         lowercase__    :   List[str]      =       model(a						,   pixel_values=a						,   training=a)
         lowercase__    :   Any      =       model(
             a						,   bbox=a						,   pixel_values=a						,   attention_mask=a						,   token_type_ids=a						,   training=a						,   )
         lowercase__    :   List[Any]      =       model(a						,   bbox=a						,   pixel_values=a						,   training=a)

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

         # text only
         lowercase__    :   List[Any]      =       model(a						,   training=a)
         self.parent.assertEqual(
             result.last_hidden_state.shape						,   (self.batch_size, self.text_seq_length, self.hidden_size))

         # image only
         lowercase__    :   Dict      =       model({'pixel_values': pixel_values}						,   training=a)
         self.parent.assertEqual(
             result.last_hidden_state.shape						,   (self.batch_size, self.image_seq_length, self.hidden_size))





    def       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a						,   a						,   a):
         lowercase__    :   Optional[Any]      =       self.num_labels
         lowercase__    :   Optional[Any]      =       TFLayoutLMvaForSequenceClassification(config=a)
         lowercase__    :   List[str]      =       model(
             a						,   bbox=a						,   pixel_values=a						,   attention_mask=a						,   token_type_ids=a						,   labels=a						,   training=a						,   )
         self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels))





    def       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a						,   a						,   a):
         lowercase__    :   Tuple      =       self.num_labels
         lowercase__    :   Dict      =       TFLayoutLMvaForTokenClassification(config=a)
         lowercase__    :   Any      =       model(
             a						,   bbox=a						,   pixel_values=a						,   attention_mask=a						,   token_type_ids=a						,   labels=a						,   training=a						,   )
         self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.text_seq_length, self.num_labels))





    def       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a						,   a						,   a):
         lowercase__    :   Optional[int]      =       2
         lowercase__    :   List[str]      =       TFLayoutLMvaForQuestionAnswering(config=a)
         lowercase__    :   Tuple      =       model(
             a						,   bbox=a						,   pixel_values=a						,   attention_mask=a						,   token_type_ids=a						,   start_positions=a						,   end_positions=a						,   training=a						,   )
         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       snake_case_				(      self):
         lowercase__    :   Union[str, Any]      =       self.prepare_config_and_inputs()
         ((lowercase__)      , (lowercase__)      , (lowercase__)      , (lowercase__)      , (lowercase__)      , (lowercase__)      , (lowercase__)      , (lowercase__))    :   Optional[Any]      =       config_and_inputs
         lowercase__    :   Optional[Any]      =       {
             '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_tf
class       SCREAMING_SNAKE_CASE__					(__snake_case		,       __snake_case		,       unittest.TestCase     ):
    __lowerCamelCase						:       List[str]														=     (
        (
            TFLayoutLMvaModel,
            TFLayoutLMvaForQuestionAnswering,
            TFLayoutLMvaForSequenceClassification,
            TFLayoutLMvaForTokenClassification,
        )
        if is_tf_available()
        else ()
    )
    __lowerCamelCase						:       Dict														=     (
        {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel}
        if is_tf_available()
        else {}
    )

    __lowerCamelCase						:       Optional[Any]														=     False
    __lowerCamelCase						:       int														=     False
    __lowerCamelCase						:       int														=     False





    def       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a):
         return True





    def       snake_case_				(      self						,   a						,   a						,   a=False):
         lowercase__    :   Tuple      =       copy.deepcopy(a)

         if model_class in get_values(a):
              lowercase__    :   Optional[Any]      =       {
                  k: tf.tile(tf.expand_dims(a						,   1)						,   (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1))
                  if isinstance(a						,   tf.Tensor) and v.ndim > 0
                  else v
                  for k, v in inputs_dict.items()
              }

         if return_labels:
              if model_class in get_values(a):
                   lowercase__    :   Union[str, Any]      =       tf.ones(self.model_tester.batch_size						,   dtype=tf.intaa)
              elif model_class in get_values(a):
                   lowercase__    :   Dict      =       tf.zeros(self.model_tester.batch_size						,   dtype=tf.intaa)
                   lowercase__    :   Optional[int]      =       tf.zeros(self.model_tester.batch_size						,   dtype=tf.intaa)
              elif model_class in get_values(a):
                   lowercase__    :   Optional[Any]      =       tf.zeros(self.model_tester.batch_size						,   dtype=tf.intaa)
              elif model_class in get_values(a):
                   lowercase__    :   Optional[int]      =       tf.zeros(
                       (self.model_tester.batch_size, self.model_tester.text_seq_length)						,   dtype=tf.intaa)

         return inputs_dict





    def       snake_case_				(      self):
         lowercase__    :   Tuple      =       TFLayoutLMvaModelTester(self)
         lowercase__    :   Optional[Any]      =       ConfigTester(self						,   config_class=a						,   hidden_size=37)





    def       snake_case_				(      self):
         self.config_tester.run_common_tests()





    def       snake_case_				(      self):
         lowercase__      , lowercase__    :   List[Any]      =       self.model_tester.prepare_config_and_inputs_for_common()
         for model_class in self.all_model_classes:
              lowercase__    :   List[Any]      =       model_class(a)
              if getattr(a						,   'hf_compute_loss'						,   a):
                   # The number of elements in the loss should be the same as the number of elements in the label
                   lowercase__    :   Optional[int]      =       self._prepare_for_class(inputs_dict.copy()						,   a						,   return_labels=a)
                   lowercase__    :   Union[str, Any]      =       prepared_for_class[
                       sorted(prepared_for_class.keys() - inputs_dict.keys()						,   reverse=a)[0]
                   ]
                   lowercase__    :   Tuple      =       added_label.shape.as_list()[:1]

                   # Test that model correctly compute the loss with kwargs
                   lowercase__    :   Dict      =       self._prepare_for_class(inputs_dict.copy()						,   a						,   return_labels=a)
                   lowercase__    :   int      =       prepared_for_class.pop('input_ids')

                   lowercase__    :   Optional[int]      =       model(a						,   **a)[0]
                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

                   # Test that model correctly compute the loss when we mask some positions
                   lowercase__    :   str      =       self._prepare_for_class(inputs_dict.copy()						,   a						,   return_labels=a)
                   lowercase__    :   str      =       prepared_for_class.pop('input_ids')
                   if "labels" in prepared_for_class:
                        lowercase__    :   Optional[Any]      =       prepared_for_class['labels'].numpy()
                        if len(labels.shape) > 1 and labels.shape[1] != 1:
                             lowercase__    :   Union[str, Any]      =       -100
                             lowercase__    :   Optional[Any]      =       tf.convert_to_tensor(a)
                             lowercase__    :   Any      =       model(a						,   **a)[0]
                             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
                             self.assertTrue(not np.any(np.isnan(loss.numpy())))

                # Test that model correctly compute the loss with a dict
                   lowercase__    :   List[Any]      =       self._prepare_for_class(inputs_dict.copy()						,   a						,   return_labels=a)
                   lowercase__    :   Optional[Any]      =       model(a)[0]
                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

                   # Test that model correctly compute the loss with a tuple
                   lowercase__    :   List[str]      =       self._prepare_for_class(inputs_dict.copy()						,   a						,   return_labels=a)

                   # Get keys that were added with the _prepare_for_class function
                   lowercase__    :   int      =       prepared_for_class.keys() - inputs_dict.keys()
                   lowercase__    :   List[Any]      =       inspect.signature(model.call).parameters
                   lowercase__    :   List[str]      =       list(signature.keys())

                   # Create a dictionary holding the location of the tensors in the tuple
                   lowercase__    :   Dict      =       {0: 'input_ids'}
                   for label_key in label_keys:
                        lowercase__    :   Tuple      =       signature_names.index(a)
                        lowercase__    :   List[str]      =       label_key
                   lowercase__    :   int      =       sorted(tuple_index_mapping.items())
                   # Initialize a list with their default values, update the values and convert to a tuple
                   lowercase__    :   List[Any]      =       []

                   for name in signature_names:
                        if name != "kwargs":
                             list_input.append(signature[name].default)

                   for index, value in sorted_tuple_index_mapping:
                        lowercase__    :   Optional[int]      =       prepared_for_class[value]

                   lowercase__    :   Any      =       tuple(a)

                   # Send to model
                   lowercase__    :   List[str]      =       model(tuple_input[:-1])[0]

                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])





    def       snake_case_				(      self):
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   List[Any]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(a						,   a						,   a						,   a						,   a						,   a)





    def       snake_case_				(      self):
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   int      =       self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
              lowercase__    :   Dict      =       type
              self.model_tester.create_and_check_model(a						,   a						,   a						,   a						,   a						,   a)





    def       snake_case_				(      self):
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   Tuple      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(
             a						,   a						,   a						,   a						,   a						,   a						,   a)





    def       snake_case_				(      self):
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   Dict      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(
             a						,   a						,   a						,   a						,   a						,   a						,   a)





    def       snake_case_				(      self):
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   List[str]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(
             a						,   a						,   a						,   a						,   a						,   a						,   a)





    @slow
    def       snake_case_				(      self):
         for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              lowercase__    :   str      =       TFLayoutLMvaModel.from_pretrained(a)
              self.assertIsNotNone(a)



def 	snake_case__			(    ):



     '''simple docstring'''





     lowercase__    :   str      =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     return image


@require_tf
class       SCREAMING_SNAKE_CASE__					(unittest.TestCase     ):





    @cached_property
    def       snake_case_				(      self):
         return LayoutLMvaImageProcessor(apply_ocr=a) if is_vision_available() else None





    @slow
    def       snake_case_				(      self):
         lowercase__    :   Optional[int]      =       TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base')

         lowercase__    :   Tuple      =       self.default_image_processor
         lowercase__    :   Union[str, Any]      =       prepare_img()
         lowercase__    :   Optional[int]      =       image_processor(images=a						,   return_tensors='tf').pixel_values

         lowercase__    :   List[Any]      =       tf.constant([[1, 2]])
         lowercase__    :   str      =       tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]])						,   axis=0)

         # forward pass
         lowercase__    :   List[str]      =       model(input_ids=a						,   bbox=a						,   pixel_values=a						,   training=a)

         # verify the logits
         lowercase__    :   Optional[int]      =       (1, 199, 768)
         self.assertEqual(outputs.last_hidden_state.shape						,   a)

         lowercase__    :   Union[str, Any]      =       tf.constant(
             [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]])

         self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]						,   a						,   atol=1e-4))

