
"""simple docstring"""



import unittest

import numpy as np

from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
from transformers.pipelines import AudioClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torchaudio,
    slow,
)

from .test_pipelines_common import ANY





@is_pipeline_test
class 				a			(					unittest.TestCase      ):
      UpperCamelCase							:   int           =     MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
      UpperCamelCase							:   List[Any]           =     TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING



      def  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          UpperCAmelCase__	:      Tuple     							=					AudioClassificationPipeline(model=UpperCamelCase_     ,	feature_extractor=UpperCamelCase_      )

          # test with a raw waveform
          UpperCAmelCase__	:      List[Any]     							=					np.zeros((34_000,)      )
          UpperCAmelCase__	:      List[Any]     							=					np.zeros((14_000,)      )
          return audio_classifier, [audioa, audio]



      def  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          UpperCAmelCase__							,							UpperCAmelCase__	:      Dict     							=					examples
          UpperCAmelCase__	:      str     							=					audio_classifier(UpperCamelCase_      )
          # by default a model is initialized with num_labels=2
          self.assertEqual(
              UpperCamelCase_     ,	[
                  {'score': ANY(UpperCamelCase_      ), 'label': ANY(UpperCamelCase_      )},
                  {'score': ANY(UpperCamelCase_      ), 'label': ANY(UpperCamelCase_      )},
              ]     ,	)
          UpperCAmelCase__	:      str     							=					audio_classifier(UpperCamelCase_     ,	top_k=1      )
          self.assertEqual(
              UpperCamelCase_     ,	[
                  {'score': ANY(UpperCamelCase_      ), 'label': ANY(UpperCamelCase_      )},
              ]     ,	)

          self.run_torchaudio(UpperCamelCase_      )



      @require_torchaudio
      def  __snake_case							(   self     ,	UpperCamelCase_      ):
          import datasets

          # test with a local file
          UpperCAmelCase__	:      Dict     							=					datasets.load_dataset('hf-internal-testing/librispeech_asr_dummy'     ,	'clean'     ,	split='validation'      )
          UpperCAmelCase__	:      List[Any]     							=					dataset[0]['audio']['array']
          UpperCAmelCase__	:      Tuple     							=					audio_classifier(UpperCamelCase_      )
          self.assertEqual(
              UpperCamelCase_     ,	[
                  {'score': ANY(UpperCamelCase_      ), 'label': ANY(UpperCamelCase_      )},
                  {'score': ANY(UpperCamelCase_      ), 'label': ANY(UpperCamelCase_      )},
              ]     ,	)



      @require_torch
      def  __snake_case							(   self      ):
          UpperCAmelCase__	:      List[Any]     							=					'anton-l/wav2vec2-random-tiny-classifier'

          UpperCAmelCase__	:      List[str]     							=					pipeline('audio-classification'     ,	model=UpperCamelCase_      )

          UpperCAmelCase__	:      List[Any]     							=					np.ones((8_000,)      )
          UpperCAmelCase__	:      Optional[int]     							=					audio_classifier(UpperCamelCase_     ,	top_k=4      )

          UpperCAmelCase__	:      List[str]     							=					[
              {'score': 0.0842, 'label': 'no'},
              {'score': 0.0838, 'label': 'up'},
              {'score': 0.0837, 'label': 'go'},
              {'score': 0.0834, 'label': 'right'},
          ]
          UpperCAmelCase__	:      List[str]     							=					[
              {'score': 0.0845, 'label': 'stop'},
              {'score': 0.0844, 'label': 'on'},
              {'score': 0.0841, 'label': 'right'},
              {'score': 0.0834, 'label': 'left'},
          ]
          self.assertIn(nested_simplify(UpperCamelCase_     ,	decimals=4      )     ,	[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]      )

          UpperCAmelCase__	:      Dict     							=					{'array': np.ones((8_000,)      ), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate}
          UpperCAmelCase__	:      Union[str, Any]     							=					audio_classifier(UpperCamelCase_     ,	top_k=4      )
          self.assertIn(nested_simplify(UpperCamelCase_     ,	decimals=4      )     ,	[EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]      )



      @require_torch
      @slow
      def  __snake_case							(   self      ):
          import datasets

          UpperCAmelCase__	:      List[Any]     							=					'superb/wav2vec2-base-superb-ks'

          UpperCAmelCase__	:      List[Any]     							=					pipeline('audio-classification'     ,	model=UpperCamelCase_      )
          UpperCAmelCase__	:      Optional[Any]     							=					datasets.load_dataset('anton-l/superb_dummy'     ,	'ks'     ,	split='test'      )

          UpperCAmelCase__	:      List[Any]     							=					np.array(dataset[3]['speech']     ,	dtype=np.floataa      )
          UpperCAmelCase__	:      Any     							=					audio_classifier(UpperCamelCase_     ,	top_k=4      )
          self.assertEqual(
              nested_simplify(UpperCamelCase_     ,	decimals=3      )     ,	[
                  {'score': 0.981, 'label': 'go'},
                  {'score': 0.007, 'label': 'up'},
                  {'score': 0.006, 'label': '_unknown_'},
                  {'score': 0.001, 'label': 'down'},
              ]     ,	)



      @require_tf
      @unittest.skip('Audio classification is not implemented for TF'      )
      def  __snake_case							(   self      ):
          pass



"""simple docstring"""



import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType





class 				a			(					lowercase      ):
      UpperCamelCase							:   Tuple           =     ["""image_processor""", """tokenizer"""]
      UpperCamelCase							:   List[str]           =     """LayoutLMv2ImageProcessor"""
      UpperCamelCase							:   Optional[int]           =     ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""")



      def __init__(   self     ,	UpperCamelCase_=None     ,	UpperCamelCase_=None     ,	**UpperCamelCase_      ):
          if "feature_extractor" in kwargs:
              warnings.warn(
                  'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                  ' instead.'     ,	UpperCamelCase_     ,	)
              UpperCAmelCase__	:      Tuple     							=					kwargs.pop('feature_extractor'      )

          UpperCAmelCase__	:      Optional[Any]     							=					image_processor if image_processor is not None else feature_extractor
          if image_processor is None:
              raise ValueError('You need to specify an `image_processor`.'      )
          if tokenizer is None:
              raise ValueError('You need to specify a `tokenizer`.'      )

          super().__init__(UpperCamelCase_     ,	UpperCamelCase_      )



      def __call__(   self     ,	UpperCamelCase_     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = True     ,	UpperCamelCase_ = False     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = 0     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = None     ,	UpperCamelCase_ = False     ,	UpperCamelCase_ = False     ,	UpperCamelCase_ = False     ,	UpperCamelCase_ = False     ,	UpperCamelCase_ = True     ,	UpperCamelCase_ = None     ,	**UpperCamelCase_     ,	):
          # verify input
          if self.image_processor.apply_ocr and (boxes is not None):
              raise ValueError(
                  'You cannot provide bounding boxes '
                  'if you initialized the image processor with apply_ocr set to True.'      )

          if self.image_processor.apply_ocr and (word_labels is not None):
              raise ValueError(
                  'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.'      )

          if return_overflowing_tokens is True and return_offsets_mapping is False:
              raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.'      )

          # first, apply the image processor
          UpperCAmelCase__	:      List[Any]     							=					self.image_processor(images=UpperCamelCase_     ,	return_tensors=UpperCamelCase_      )

          # second, apply the tokenizer
          if text is not None and self.image_processor.apply_ocr and text_pair is None:
              if isinstance(UpperCamelCase_     ,	UpperCamelCase_      ):
                  UpperCAmelCase__	:      Any     							=					[text]  # add batch dimension (as the image processor always adds a batch dimension)
              UpperCAmelCase__	:      Union[str, Any]     							=					features['words']

          UpperCAmelCase__	:      List[Any]     							=					self.tokenizer(
              text=text if text is not None else features['words']     ,	text_pair=text_pair if text_pair is not None else None     ,	boxes=boxes if boxes is not None else features['boxes']     ,	word_labels=UpperCamelCase_     ,	add_special_tokens=UpperCamelCase_     ,	padding=UpperCamelCase_     ,	truncation=UpperCamelCase_     ,	max_length=UpperCamelCase_     ,	stride=UpperCamelCase_     ,	pad_to_multiple_of=UpperCamelCase_     ,	return_token_type_ids=UpperCamelCase_     ,	return_attention_mask=UpperCamelCase_     ,	return_overflowing_tokens=UpperCamelCase_     ,	return_special_tokens_mask=UpperCamelCase_     ,	return_offsets_mapping=UpperCamelCase_     ,	return_length=UpperCamelCase_     ,	verbose=UpperCamelCase_     ,	return_tensors=UpperCamelCase_     ,	**UpperCamelCase_     ,	)

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

          return encoded_inputs



      def  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
          UpperCAmelCase__	:      Dict     							=					[]
          for sample_idx in overflow_to_sample_mapping:
              images_with_overflow.append(images[sample_idx]      )

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

          return images_with_overflow



      def  __snake_case							(   self     ,	*UpperCamelCase_     ,	**UpperCamelCase_      ):
          return self.tokenizer.batch_decode(*UpperCamelCase_     ,	**UpperCamelCase_      )



      def  __snake_case							(   self     ,	*UpperCamelCase_     ,	**UpperCamelCase_      ):
          return self.tokenizer.decode(*UpperCamelCase_     ,	**UpperCamelCase_      )



      @property
      def  __snake_case							(   self      ):
          return ["input_ids", "bbox", "attention_mask", "image"]



      @property
      def  __snake_case							(   self      ):
          warnings.warn(
              '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'     ,	UpperCamelCase_     ,	)
          return self.image_processor_class



      @property
      def  __snake_case							(   self      ):
          warnings.warn(
              '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'     ,	UpperCamelCase_     ,	)
          return self.image_processor

