



'''simple docstring'''





import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase_									=    random.Random()

if is_torch_available():
  import torch




def lowerCAmelCase    (__A    ,      __A=1.0    ,      __A=None    ,      __A=None):



     """simple docstring"""



     if rng is None:
          _a           =    global_rng

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

     return values






class __A     (    unittest.TestCase		):



 '''simple docstring'''







 def __init__(self					,  A					,  A=7					,  A=400					,  A=2_000					,  A=1					,  A=0.0					,  A=16_000					,  A=True					,  A=True					,  )       ->	Optional[Any]:


      """simple docstring"""



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



 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



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



 def    a__    (self					,  A=False					,  A=False			)       ->	Optional[Any]:


      """simple docstring"""



      def _flatten(A			):
           return list(itertools.chain(*A			)			)

      if equal_length:
           _a           =    floats_list((self.batch_size, self.max_seq_length)			)
      else:
           # make sure that inputs increase in size
           _a           =    [
               _flatten(floats_list((x, self.feature_size)			)			)
               for x in range(self.min_seq_length					,  self.max_seq_length					,  self.seq_length_diff			)
           ]

      if numpify:
           _a           =    [np.asarray(A			) for x in speech_inputs]

      return speech_inputs






@require_torch
@require_torchaudio
class __A     (    A  ,  unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			int		=			ASTFeatureExtractor



 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



      _a           =    ASTFeatureExtractionTester(self			)



 def    a__    (self			)       ->	Dict:


      """simple docstring"""



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

      # Test not batched input
      _a           =    feat_extract(speech_inputs[0]					,  return_tensors='''np'''			).input_values
      _a           =    feat_extract(np_speech_inputs[0]					,  return_tensors='''np'''			).input_values
      self.assertTrue(np.allclose(A					,  A					,  atol=1E-3			)			)

      # Test batched
      _a           =    feat_extract(A					,  padding=A					,  return_tensors='''np'''			).input_values
      _a           =    feat_extract(A					,  padding=A					,  return_tensors='''np'''			).input_values
      for enc_seq_a, enc_seq_a in zip(A					,  A			):
           self.assertTrue(np.allclose(A					,  A					,  atol=1E-3			)			)

      # Test 2-D numpy arrays are batched.
      _a           =    [floats_list((1, x)			)[0] for x in (800, 800, 800)]
      _a           =    np.asarray(A			)
      _a           =    feat_extract(A					,  return_tensors='''np'''			).input_values
      _a           =    feat_extract(A					,  return_tensors='''np'''			).input_values
      for enc_seq_a, enc_seq_a in zip(A					,  A			):
           self.assertTrue(np.allclose(A					,  A					,  atol=1E-3			)			)



 @require_torch
 def    a__    (self			)       ->	Union[str, Any]:


      """simple docstring"""



      import torch

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

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



 def    a__    (self					,  A			)       ->	Optional[Any]:


      """simple docstring"""



      from datasets import load_dataset

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

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



 @require_torch
 def    a__    (self			)       ->	Union[str, Any]:


      """simple docstring"""



      _a           =    torch.tensor(
          [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
           -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
           -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
           -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]			)
      # fmt: on

      _a           =    self._load_datasamples(1			)
      _a           =    ASTFeatureExtractor()
      _a           =    feature_extractor(A					,  return_tensors='''pt'''			).input_values
      self.assertEquals(input_values.shape					,  (1, 1_024, 128)			)
      self.assertTrue(torch.allclose(input_values[0, 0, :30]					,  A					,  atol=1E-4			)			)









'''simple docstring'''
import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import DonutImageProcessor
class   __UpperCAmelCase				(     unittest.TestCase				):



					'''simple docstring'''





					def __init__(	self     :						int      ,       _lowercase     :						Any      ,       _lowercase     :						Tuple=7      ,       _lowercase     :						Tuple=3      ,       _lowercase     :						str=18      ,       _lowercase     :						Union[str, Any]=30      ,       _lowercase     :						Dict=400      ,       _lowercase     :						int=True      ,       _lowercase     :						List[Any]=None      ,       _lowercase     :						int=True      ,       _lowercase     :						Optional[int]=False      ,       _lowercase     :						str=True      ,       _lowercase     :						Union[str, Any]=True      ,       _lowercase     :						Any=[0.5, 0.5, 0.5]      ,       _lowercase     :						str=[0.5, 0.5, 0.5]      ,       )    ->							Optional[Any]:
								A_									= parent
								A_									= batch_size
								A_									= num_channels
								A_									= image_size
								A_									= min_resolution
								A_									= max_resolution
								A_									= do_resize
								A_									= size if size is not None else {'height': 18, 'width': 20}
								A_									= do_thumbnail
								A_									= do_align_axis
								A_									= do_pad
								A_									= do_normalize
								A_									= image_mean
								A_									= image_std



					def     __snake_case						(	self     :						int)    ->							int:
								return {
								    "do_resize": self.do_resize,
								    "size": self.size,
								    "do_thumbnail": self.do_thumbnail,
								    "do_align_long_axis": self.do_align_axis,
								    "do_pad": self.do_pad,
								    "do_normalize": self.do_normalize,
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								}





@require_torch
@require_vision
class   __UpperCAmelCase				(     lowerCAmelCase			,unittest.TestCase				):



					'''simple docstring'''





					_UpperCamelCase							=		DonutImageProcessor if is_vision_available() else None



					def     __snake_case						(	self     :						Optional[int])    ->							Union[str, Any]:
								A_									= DonutImageProcessingTester(self)



					@property
					def     __snake_case						(	self     :						int)    ->							int:
								return self.image_processor_tester.prepare_image_processor_dict()



					def     __snake_case						(	self     :						Any)    ->							Tuple:
								A_									= self.image_processing_class(**self.image_processor_dict)
								self.assertTrue(hasattr(_lowercase      ,       'do_resize'))
								self.assertTrue(hasattr(_lowercase      ,       'size'))
								self.assertTrue(hasattr(_lowercase      ,       'do_thumbnail'))
								self.assertTrue(hasattr(_lowercase      ,       'do_align_long_axis'))
								self.assertTrue(hasattr(_lowercase      ,       'do_pad'))
								self.assertTrue(hasattr(_lowercase      ,       'do_normalize'))
								self.assertTrue(hasattr(_lowercase      ,       'image_mean'))
								self.assertTrue(hasattr(_lowercase      ,       'image_std'))



					def     __snake_case						(	self     :						int)    ->							Optional[int]:
								A_									= self.image_processing_class.from_dict(self.image_processor_dict)
								self.assertEqual(image_processor.size      ,       {'height': 18, 'width': 20})

								A_									= self.image_processing_class.from_dict(self.image_processor_dict      ,       size=42)
								self.assertEqual(image_processor.size      ,       {'height': 42, 'width': 42})

								# Previous config had dimensions in (width, height) order
								A_									= self.image_processing_class.from_dict(self.image_processor_dict      ,       size=(42, 84))
								self.assertEqual(image_processor.size      ,       {'height': 84, 'width': 42})



					def     __snake_case						(	self     :						Optional[Any])    ->							Optional[Any]:
								pass



					@is_flaky()
					def     __snake_case						(	self     :						List[str])    ->							int:
								# Initialize image_processing
								A_									= self.image_processing_class(**self.image_processor_dict)
								# create random PIL images
								A_									= prepare_image_inputs(self.image_processor_tester      ,       equal_resolution=_lowercase)
								for image in image_inputs:
											self.assertIsInstance(_lowercase      ,       Image.Image)

								# Test not batched input
								A_									= image_processing(image_inputs[0]      ,       return_tensors='pt').pixel_values
								self.assertEqual(
								    encoded_images.shape      ,       (
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['height'],
								        self.image_processor_tester.size['width'],
								    )      ,       )

								# Test batched
								A_									= image_processing(_lowercase      ,       return_tensors='pt').pixel_values
								self.assertEqual(
								    encoded_images.shape      ,       (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['height'],
								        self.image_processor_tester.size['width'],
								    )      ,       )



					@is_flaky()
					def     __snake_case						(	self     :						List[Any])    ->							List[Any]:
								# Initialize image_processing
								A_									= self.image_processing_class(**self.image_processor_dict)
								# create random numpy tensors
								A_									= prepare_image_inputs(self.image_processor_tester      ,       equal_resolution=_lowercase      ,       numpify=_lowercase)
								for image in image_inputs:
											self.assertIsInstance(_lowercase      ,       np.ndarray)

								# Test not batched input
								A_									= image_processing(image_inputs[0]      ,       return_tensors='pt').pixel_values
								self.assertEqual(
								    encoded_images.shape      ,       (
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['height'],
								        self.image_processor_tester.size['width'],
								    )      ,       )

								# Test batched
								A_									= image_processing(_lowercase      ,       return_tensors='pt').pixel_values
								self.assertEqual(
								    encoded_images.shape      ,       (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['height'],
								        self.image_processor_tester.size['width'],
								    )      ,       )



					@is_flaky()
					def     __snake_case						(	self     :						Dict)    ->							int:
								# Initialize image_processing
								A_									= self.image_processing_class(**self.image_processor_dict)
								# create random PyTorch tensors
								A_									= prepare_image_inputs(self.image_processor_tester      ,       equal_resolution=_lowercase      ,       torchify=_lowercase)
								for image in image_inputs:
											self.assertIsInstance(_lowercase      ,       torch.Tensor)

								# Test not batched input
								A_									= image_processing(image_inputs[0]      ,       return_tensors='pt').pixel_values
								self.assertEqual(
								    encoded_images.shape      ,       (
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['height'],
								        self.image_processor_tester.size['width'],
								    )      ,       )

								# Test batched
								A_									= image_processing(_lowercase      ,       return_tensors='pt').pixel_values
								self.assertEqual(
								    encoded_images.shape      ,       (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['height'],
								        self.image_processor_tester.size['width'],
								    )      ,       )




