
'''simple docstring'''


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     lowercase__						:






   '''simple docstring'''







   def __init__(      self			, lowerCamelCase__			, lowerCamelCase__=2			, lowerCamelCase__=3			, lowerCamelCase__=4			, lowerCamelCase__=2			, lowerCamelCase__=7			, lowerCamelCase__=True			, lowerCamelCase__=True			, lowerCamelCase__=True			, lowerCamelCase__=True			, lowerCamelCase__=9_9			, lowerCamelCase__=3_6			, lowerCamelCase__=2			, lowerCamelCase__=4			, lowerCamelCase__=3_7			, lowerCamelCase__="gelu"			, lowerCamelCase__=0.1			, lowerCamelCase__=0.1			, lowerCamelCase__=5_1_2			, lowerCamelCase__=1_6			, lowerCamelCase__=2			, lowerCamelCase__=0.02			, lowerCamelCase__=6			, lowerCamelCase__=6			, lowerCamelCase__=3			, lowerCamelCase__=4			, lowerCamelCase__=None			, lowerCamelCase__=1_0_0_0			, ):

      '''simple docstring'''







      UpperCamelCase	  =	parent
      UpperCamelCase	  =	batch_size
      UpperCamelCase	  =	num_channels
      UpperCamelCase	  =	image_size
      UpperCamelCase	  =	patch_size
      UpperCamelCase	  =	is_training
      UpperCamelCase	  =	use_input_mask
      UpperCamelCase	  =	use_token_type_ids
      UpperCamelCase	  =	use_labels
      UpperCamelCase	  =	vocab_size
      UpperCamelCase	  =	hidden_size
      UpperCamelCase	  =	num_hidden_layers
      UpperCamelCase	  =	num_attention_heads
      UpperCamelCase	  =	intermediate_size
      UpperCamelCase	  =	hidden_act
      UpperCamelCase	  =	hidden_dropout_prob
      UpperCamelCase	  =	attention_probs_dropout_prob
      UpperCamelCase	  =	max_position_embeddings
      UpperCamelCase	  =	type_vocab_size
      UpperCamelCase	  =	type_sequence_label_size
      UpperCamelCase	  =	initializer_range
      UpperCamelCase	  =	coordinate_size
      UpperCamelCase	  =	shape_size
      UpperCamelCase	  =	num_labels
      UpperCamelCase	  =	num_choices
      UpperCamelCase	  =	scope
      UpperCamelCase	  =	range_bbox

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







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      UpperCamelCase	  =	ids_tensor([self.batch_size, self.text_seq_length]			, self.vocab_size )

      UpperCamelCase	  =	ids_tensor([self.batch_size, self.text_seq_length, 4]			, self.range_bbox )
      UpperCamelCase	  =	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]:
               UpperCamelCase	  =	bbox[i, j, 3]
               UpperCamelCase	  =	bbox[i, j, 1]
               UpperCamelCase	  =	tmp_coordinate
            if bbox[i, j, 2] < bbox[i, j, 0]:
               UpperCamelCase	  =	bbox[i, j, 2]
               UpperCamelCase	  =	bbox[i, j, 0]
               UpperCamelCase	  =	tmp_coordinate
      UpperCamelCase	  =	tf.constant(lowercase_ )

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

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

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

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

      UpperCamelCase	  =	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    UpperCAmelCase					(      self			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__ ):

      '''simple docstring'''







      UpperCamelCase	  =	TFLayoutLMvaModel(config=lowercase_ )

      # text + image
      UpperCamelCase	  =	model(lowercase_			, pixel_values=lowercase_			, training=lowercase_ )
      UpperCamelCase	  =	model(
          lowercase_			, bbox=lowercase_			, pixel_values=lowercase_			, attention_mask=lowercase_			, token_type_ids=lowercase_			, training=lowercase_			, )
      UpperCamelCase	  =	model(lowercase_			, bbox=lowercase_			, pixel_values=lowercase_			, training=lowercase_ )

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

      # text only
      UpperCamelCase	  =	model(lowercase_			, training=lowercase_ )
      self.parent.assertEqual(
          result.last_hidden_state.shape			, (self.batch_size, self.text_seq_length, self.hidden_size) )

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







   def    UpperCAmelCase					(      self			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__ ):

      '''simple docstring'''







      UpperCamelCase	  =	self.num_labels
      UpperCamelCase	  =	TFLayoutLMvaForSequenceClassification(config=lowercase_ )
      UpperCamelCase	  =	model(
          lowercase_			, bbox=lowercase_			, pixel_values=lowercase_			, attention_mask=lowercase_			, token_type_ids=lowercase_			, labels=lowercase_			, training=lowercase_			, )
      self.parent.assertEqual(result.logits.shape			, (self.batch_size, self.num_labels) )







   def    UpperCAmelCase					(      self			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__ ):

      '''simple docstring'''







      UpperCamelCase	  =	self.num_labels
      UpperCamelCase	  =	TFLayoutLMvaForTokenClassification(config=lowercase_ )
      UpperCamelCase	  =	model(
          lowercase_			, bbox=lowercase_			, pixel_values=lowercase_			, attention_mask=lowercase_			, token_type_ids=lowercase_			, labels=lowercase_			, training=lowercase_			, )
      self.parent.assertEqual(result.logits.shape			, (self.batch_size, self.text_seq_length, self.num_labels) )







   def    UpperCAmelCase					(      self			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__ ):

      '''simple docstring'''







      UpperCamelCase	  =	2
      UpperCamelCase	  =	TFLayoutLMvaForQuestionAnswering(config=lowercase_ )
      UpperCamelCase	  =	model(
          lowercase_			, bbox=lowercase_			, pixel_values=lowercase_			, attention_mask=lowercase_			, token_type_ids=lowercase_			, start_positions=lowercase_			, end_positions=lowercase_			, training=lowercase_			, )
      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    UpperCAmelCase					(      self ):

      '''simple docstring'''







      UpperCamelCase	  =	self.prepare_config_and_inputs()
      ((UpperCamelCase)  ,			(UpperCamelCase)  ,			(UpperCamelCase)  ,			(UpperCamelCase)  ,			(UpperCamelCase)  ,			(UpperCamelCase)  ,			(UpperCamelCase)  ,			(UpperCamelCase))	  =	config_and_inputs
      UpperCamelCase	  =	{
          '''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     lowercase__						(	snake_case_,       snake_case_,       unittest.TestCase ):






   '''simple docstring'''







   _snake_case		 =				(
       (
           TFLayoutLMvaModel,
           TFLayoutLMvaForQuestionAnswering,
           TFLayoutLMvaForSequenceClassification,
           TFLayoutLMvaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   _snake_case		 =				(
       {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
       if is_tf_available()
       else {}
   )

   _snake_case		 =				False
   _snake_case		 =				False
   _snake_case		 =				False







   def    UpperCAmelCase					(      self			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__ ):

      '''simple docstring'''







      return True







   def    UpperCAmelCase					(      self			, lowerCamelCase__			, lowerCamelCase__			, lowerCamelCase__=False ):

      '''simple docstring'''







      UpperCamelCase	  =	copy.deepcopy(lowercase_ )

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

      if return_labels:
         if model_class in get_values(lowercase_ ):
            UpperCamelCase	  =	tf.ones(self.model_tester.batch_size			, dtype=tf.intaa )
         elif model_class in get_values(lowercase_ ):
            UpperCamelCase	  =	tf.zeros(self.model_tester.batch_size			, dtype=tf.intaa )
            UpperCamelCase	  =	tf.zeros(self.model_tester.batch_size			, dtype=tf.intaa )
         elif model_class in get_values(lowercase_ ):
            UpperCamelCase	  =	tf.zeros(self.model_tester.batch_size			, dtype=tf.intaa )
         elif model_class in get_values(lowercase_ ):
            UpperCamelCase	  =	tf.zeros(
                (self.model_tester.batch_size, self.model_tester.text_seq_length)			, dtype=tf.intaa )

      return inputs_dict







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      UpperCamelCase	  =	TFLayoutLMvaModelTester(self )
      UpperCamelCase	  =	ConfigTester(self			, config_class=lowercase_			, hidden_size=3_7 )







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      self.config_tester.run_common_tests()







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      UpperCamelCase  ,			UpperCamelCase	  =	self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
         UpperCamelCase	  =	model_class(lowercase_ )
         if getattr(lowercase_			, '''hf_compute_loss'''			, lowercase_ ):
            # The number of elements in the loss should be the same as the number of elements in the label
            UpperCamelCase	  =	self._prepare_for_class(inputs_dict.copy()			, lowercase_			, return_labels=lowercase_ )
            UpperCamelCase	  =	prepared_for_class[
                sorted(prepared_for_class.keys() - inputs_dict.keys()			, reverse=lowercase_ )[0]
            ]
            UpperCamelCase	  =	added_label.shape.as_list()[:1]

            # Test that model correctly compute the loss with kwargs
            UpperCamelCase	  =	self._prepare_for_class(inputs_dict.copy()			, lowercase_			, return_labels=lowercase_ )
            UpperCamelCase	  =	prepared_for_class.pop('''input_ids''' )

            UpperCamelCase	  =	model(lowercase_			, **lowercase_ )[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
            UpperCamelCase	  =	self._prepare_for_class(inputs_dict.copy()			, lowercase_			, return_labels=lowercase_ )
            UpperCamelCase	  =	prepared_for_class.pop('''input_ids''' )
            if "labels" in prepared_for_class:
               UpperCamelCase	  =	prepared_for_class['''labels'''].numpy()
               if len(labels.shape ) > 1 and labels.shape[1] != 1:
                  UpperCamelCase	  =	-1_0_0
                  UpperCamelCase	  =	tf.convert_to_tensor(lowercase_ )
                  UpperCamelCase	  =	model(lowercase_			, **lowercase_ )[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
            UpperCamelCase	  =	self._prepare_for_class(inputs_dict.copy()			, lowercase_			, return_labels=lowercase_ )
            UpperCamelCase	  =	model(lowercase_ )[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
            UpperCamelCase	  =	self._prepare_for_class(inputs_dict.copy()			, lowercase_			, return_labels=lowercase_ )

            # Get keys that were added with the _prepare_for_class function
            UpperCamelCase	  =	prepared_for_class.keys() - inputs_dict.keys()
            UpperCamelCase	  =	inspect.signature(model.call ).parameters
            UpperCamelCase	  =	list(signature.keys() )

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

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

            for index, value in sorted_tuple_index_mapping:
               UpperCamelCase	  =	prepared_for_class[value]

            UpperCamelCase	  =	tuple(lowercase_ )

            # Send to model
            UpperCamelCase	  =	model(tuple_input[:-1] )[0]

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







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      (
          (
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,									
      )	  =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_ )







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      (
          (
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,									
      )	  =	self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
         UpperCamelCase	  =	type
         self.model_tester.create_and_check_model(lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_ )







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      (
          (
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,									
      )	  =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(
          lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_ )







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      (
          (
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,									
      )	  =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(
          lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_ )







   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      (
          (
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,			(
          UpperCamelCase						
      )  ,									
      )	  =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(
          lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_			, lowercase_ )







   @slow
   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         UpperCamelCase	  =	TFLayoutLMvaModel.from_pretrained(lowercase_ )
         self.assertIsNotNone(lowercase_ )




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


@require_tf
class     lowercase__						(	unittest.TestCase ):






   '''simple docstring'''







   @cached_property
   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      return LayoutLMvaImageProcessor(apply_ocr=lowercase_ ) if is_vision_available() else None







   @slow
   def    UpperCAmelCase					(      self ):

      '''simple docstring'''







      UpperCamelCase	  =	TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' )

      UpperCamelCase	  =	self.default_image_processor
      UpperCamelCase	  =	prepare_img()
      UpperCamelCase	  =	image_processor(images=lowercase_			, return_tensors='''tf''' ).pixel_values

      UpperCamelCase	  =	tf.constant([[1, 2]] )
      UpperCamelCase	  =	tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] )			, axis=0 )

      # forward pass
      UpperCamelCase	  =	model(input_ids=lowercase_			, bbox=lowercase_			, pixel_values=lowercase_			, training=lowercase_ )

      # verify the logits
      UpperCamelCase	  =	(1, 1_9_9, 7_6_8)
      self.assertEqual(outputs.last_hidden_state.shape			, lowercase_ )

      UpperCamelCase	  =	tf.constant(
          [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] )

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






import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
   from transformers import SpeechaTextFeatureExtractor

lowerCamelCase__  =					random.Random()


def 				lowerCAmelCase__       (			a__    ,     a__=1.0    ,     a__=None    ,     a__=None )      ->Optional[Any]:




  '''simple docstring'''

  if rng is None:
    _UpperCamelCase           =    global_rng

  _UpperCamelCase           =    []
  for batch_idx in range(shape[0] ):
    values.append([] )
    for _ in range(shape[1] ):
      values[-1].append(rng.random() * scale )

  return values




@require_torch
@require_torchaudio
class 					_UpperCAmelCase			(     unittest.TestCase  ):



 '''simple docstring'''




 def __init__(		self				:   Optional[Any]							, lowercase_				:   List[str]							, lowercase_				:   List[str]=7							, lowercase_				:   List[str]=400							, lowercase_				:   str=2000							, lowercase_				:   Optional[int]=24							, lowercase_				:   Optional[int]=24							, lowercase_				:   Tuple=0.0							, lowercase_				:   Any=16000							, lowercase_				:   Any=True							, lowercase_				:   Optional[int]=True							, )						->	Union[str, Any]:


   """simple docstring"""







   _UpperCamelCase           =    parent
   _UpperCamelCase           =    batch_size
   _UpperCamelCase           =    min_seq_length
   _UpperCamelCase           =    max_seq_length
   _UpperCamelCase           =    (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
   _UpperCamelCase           =    feature_size
   _UpperCamelCase           =    num_mel_bins
   _UpperCamelCase           =    padding_value
   _UpperCamelCase           =    sampling_rate
   _UpperCamelCase           =    return_attention_mask
   _UpperCamelCase           =    do_normalize







 def 		__UpperCAmelCase				(		self				:   int)						->	str:


   """simple docstring"""







   return {
       "feature_size": self.feature_size,
       "num_mel_bins": self.num_mel_bins,
       "padding_value": self.padding_value,
       "sampling_rate": self.sampling_rate,
       "return_attention_mask": self.return_attention_mask,
       "do_normalize": self.do_normalize,
   }







 def 		__UpperCAmelCase				(		self				:   Tuple							, lowercase_				:   Optional[Any]=False							, lowercase_				:   int=False)						->	Dict:


   """simple docstring"""







   def _flatten(lowercase_				:   str):
     return list(itertools.chain(*lowercase_))

   if equal_length:
     _UpperCamelCase           =    [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
   else:
     # make sure that inputs increase in size
     _UpperCamelCase           =    [
         floats_list((x, self.feature_size))
         for x in range(self.min_seq_length							, self.max_seq_length							, self.seq_length_diff)
     ]
   if numpify:
     _UpperCamelCase           =    [np.asarray(lowercase_) for x in speech_inputs]
   return speech_inputs




@require_torch
@require_torchaudio
class 					_UpperCAmelCase			(     lowerCAmelCase,			unittest.TestCase  ):



 '''simple docstring'''




 __A			       =					SpeechaTextFeatureExtractor if is_speech_available() else None







 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	List[Any]:


   """simple docstring"""







   _UpperCamelCase           =    SpeechaTextFeatureExtractionTester(self)







 def 		__UpperCAmelCase				(		self				:   Dict							, lowercase_				:   Tuple)						->	int:


   """simple docstring"""







   self.assertTrue(np.all(np.mean(lowercase_							, axis=0) < 1e-3))
   self.assertTrue(np.all(np.abs(np.var(lowercase_							, axis=0) - 1) < 1e-3))







 def 		__UpperCAmelCase				(		self				:   List[Any])						->	int:


   """simple docstring"""







   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   # create three inputs of length 800, 1000, and 1200
   _UpperCamelCase           =    [floats_list((1, x))[0] for x in range(800							, 1400							, 200)]
   _UpperCamelCase           =    [np.asarray(lowercase_) for speech_input in speech_inputs]

   # Test feature size
   _UpperCamelCase           =    feature_extractor(lowercase_							, padding=lowercase_							, return_tensors="np").input_features
   self.assertTrue(input_features.ndim == 3)
   self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size)

   # Test not batched input
   _UpperCamelCase           =    feature_extractor(speech_inputs[0]							, return_tensors="np").input_features
   _UpperCamelCase           =    feature_extractor(np_speech_inputs[0]							, return_tensors="np").input_features
   self.assertTrue(np.allclose(lowercase_							, lowercase_							, atol=1e-3))

   # Test batched
   _UpperCamelCase           =    feature_extractor(lowercase_							, return_tensors="np").input_features
   _UpperCamelCase           =    feature_extractor(lowercase_							, return_tensors="np").input_features
   for enc_seq_a, enc_seq_a in zip(lowercase_							, lowercase_):
     self.assertTrue(np.allclose(lowercase_							, lowercase_							, atol=1e-3))

   # Test 2-D numpy arrays are batched.
   _UpperCamelCase           =    [floats_list((1, x))[0] for x in (800, 800, 800)]
   _UpperCamelCase           =    np.asarray(lowercase_)
   _UpperCamelCase           =    feature_extractor(lowercase_							, return_tensors="np").input_features
   _UpperCamelCase           =    feature_extractor(lowercase_							, return_tensors="np").input_features
   for enc_seq_a, enc_seq_a in zip(lowercase_							, lowercase_):
     self.assertTrue(np.allclose(lowercase_							, lowercase_							, atol=1e-3))







 def 		__UpperCAmelCase				(		self				:   Dict)						->	List[Any]:


   """simple docstring"""







   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   _UpperCamelCase           =    [floats_list((1, x))[0] for x in range(800							, 1400							, 200)]

   _UpperCamelCase           =    ["longest", "max_length", "do_not_pad"]
   _UpperCamelCase           =    [None, 16, None]
   for max_length, padding in zip(lowercase_							, lowercase_):
     _UpperCamelCase           =    feature_extractor(
         lowercase_							, padding=lowercase_							, max_length=lowercase_							, return_attention_mask=lowercase_)
     _UpperCamelCase           =    inputs.input_features
     _UpperCamelCase           =    inputs.attention_mask
     _UpperCamelCase           =    [np.sum(lowercase_) for x in attention_mask]

     self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]])
     self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]])
     self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]])







 def 		__UpperCAmelCase				(		self				:   int)						->	str:


   """simple docstring"""







   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   _UpperCamelCase           =    [floats_list((1, x))[0] for x in range(800							, 1400							, 200)]

   _UpperCamelCase           =    ["longest", "max_length", "do_not_pad"]
   _UpperCamelCase           =    [None, 16, None]
   for max_length, padding in zip(lowercase_							, lowercase_):
     _UpperCamelCase           =    feature_extractor(
         lowercase_							, max_length=lowercase_							, padding=lowercase_							, return_tensors="np"							, return_attention_mask=lowercase_)
     _UpperCamelCase           =    inputs.input_features
     _UpperCamelCase           =    inputs.attention_mask
     _UpperCamelCase           =    [np.sum(lowercase_) for x in attention_mask]

     self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]])
     self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6)
     self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]])
     self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6)
     self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]])







 def 		__UpperCAmelCase				(		self				:   int)						->	Optional[int]:


   """simple docstring"""







   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   _UpperCamelCase           =    [floats_list((1, x))[0] for x in range(800							, 1400							, 200)]
   _UpperCamelCase           =    feature_extractor(
       lowercase_							, padding="max_length"							, max_length=4							, truncation=lowercase_							, return_tensors="np"							, return_attention_mask=lowercase_							, )
   _UpperCamelCase           =    inputs.input_features
   _UpperCamelCase           =    inputs.attention_mask
   _UpperCamelCase           =    np.sum(attention_mask == 1							, axis=1)

   self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
   self._check_zero_mean_unit_variance(input_features[1])
   self._check_zero_mean_unit_variance(input_features[2])







 def 		__UpperCAmelCase				(		self				:   Dict)						->	Optional[int]:


   """simple docstring"""







   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   _UpperCamelCase           =    [floats_list((1, x))[0] for x in range(800							, 1400							, 200)]
   _UpperCamelCase           =    feature_extractor(
       lowercase_							, padding="longest"							, max_length=4							, truncation=lowercase_							, return_tensors="np"							, return_attention_mask=lowercase_							, )
   _UpperCamelCase           =    inputs.input_features
   _UpperCamelCase           =    inputs.attention_mask
   _UpperCamelCase           =    np.sum(attention_mask == 1							, axis=1)

   self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
   self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
   self._check_zero_mean_unit_variance(input_features[2])

   # make sure that if max_length < longest -> then pad to max_length
   self.assertEqual(input_features.shape							, (3, 4, 24))

   _UpperCamelCase           =    [floats_list((1, x))[0] for x in range(800							, 1400							, 200)]
   _UpperCamelCase           =    feature_extractor(
       lowercase_							, padding="longest"							, max_length=16							, truncation=lowercase_							, return_tensors="np"							, return_attention_mask=lowercase_							, )
   _UpperCamelCase           =    inputs.input_features
   _UpperCamelCase           =    inputs.attention_mask
   _UpperCamelCase           =    np.sum(attention_mask == 1							, axis=1)

   self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
   self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
   self._check_zero_mean_unit_variance(input_features[2])

   # make sure that if max_length < longest -> then pad to max_length
   self.assertEqual(input_features.shape							, (3, 6, 24))







 def 		__UpperCAmelCase				(		self				:   Tuple)						->	Dict:


   """simple docstring"""







   import torch

   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   _UpperCamelCase           =    np.random.rand(100							, 32).astype(np.floataa)
   _UpperCamelCase           =    np_speech_inputs.tolist()

   for inputs in [py_speech_inputs, np_speech_inputs]:
     _UpperCamelCase           =    feature_extractor.pad([{"input_features": inputs}]							, return_tensors="np")
     self.assertTrue(np_processed.input_features.dtype == np.floataa)
     _UpperCamelCase           =    feature_extractor.pad([{"input_features": inputs}]							, return_tensors="pt")
     self.assertTrue(pt_processed.input_features.dtype == torch.floataa)







 def 		__UpperCAmelCase				(		self				:   str							, lowercase_				:   List[str])						->	Dict:


   """simple docstring"""







   from datasets import load_dataset

   _UpperCamelCase           =    load_dataset("hf-internal-testing/librispeech_asr_dummy"							, "clean"							, split="validation")
   # automatic decoding with librispeech
   _UpperCamelCase           =    ds.sort("id").select(range(lowercase_))[:num_samples]["audio"]

   return [x["array"] for x in speech_samples]







 def 		__UpperCAmelCase				(		self				:   str)						->	Tuple:


   """simple docstring"""







   _UpperCamelCase           =    np.array([
       -1.57_45, -1.77_13, -1.70_20, -1.60_69, -1.22_50, -1.11_05, -0.90_72, -0.82_41,
       -1.23_10, -0.80_98, -0.33_20, -0.41_01, -0.79_85, -0.49_96, -0.82_13, -0.91_28,
       -1.04_20, -1.12_86, -1.04_40, -0.79_99, -0.84_05, -1.22_75, -1.54_43, -1.46_25,
   ])
   # fmt: on

   _UpperCamelCase           =    self._load_datasamples(1)
   _UpperCamelCase           =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
   _UpperCamelCase           =    feature_extractor(lowercase_							, return_tensors="pt").input_features
   self.assertEquals(input_features.shape							, (1, 584, 24))
   self.assertTrue(np.allclose(input_features[0, 0, :30]							, lowercase_							, atol=1e-4))




