
'''simple docstring'''

import itertools
import random
import unittest

import numpy as np

from transformers import EncodecFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
 import torch


UpperCamelCase_            =    random.Random()


def 		_UpperCAmelCase			(					_lowerCamelCase  :    Dict					, _lowerCamelCase  :    Any=1.0					, _lowerCamelCase  :    Tuple=None					, _lowerCamelCase  :    Optional[int]=None						)      ->  int:
  if rng is None:
    _lowerCAmelCase    :					Union[str, Any]							=   global_rng

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

  return values


@require_torch
class 					a_					(unittest.TestCase      ):




       def __init__(       self				,				snake_case_				,				snake_case_=7				,				snake_case_=4_0_0				,				snake_case_=2_0_0_0				,				snake_case_=1				,				snake_case_=0.0				,				snake_case_=2_4_0_0_0				,				snake_case_=True				,				):
         _lowerCAmelCase    :					Optional[Any]							=   parent
         _lowerCAmelCase    :					Optional[int]							=   batch_size
         _lowerCAmelCase    :					Dict							=   min_seq_length
         _lowerCAmelCase    :					Any							=   max_seq_length
         _lowerCAmelCase    :					List[Any]							=   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         _lowerCAmelCase    :					int							=   feature_size
         _lowerCAmelCase    :					Tuple							=   padding_value
         _lowerCAmelCase    :					int							=   sampling_rate
         _lowerCAmelCase    :					Optional[int]							=   return_attention_mask




       def 							__UpperCamelCase    (       self					):
         return {
             "feature_size": self.feature_size,
             "padding_value": self.padding_value,
             "sampling_rate": self.sampling_rate,
             "return_attention_mask": self.return_attention_mask,
         }







       def 							__UpperCamelCase    (       self				,				snake_case_=False				,				snake_case_=False					):
         def _flatten(snake_case_					):
           return list(itertools.chain(*snake_case_					)					)

         if equal_length:
           _lowerCAmelCase    :					List[Any]							=   floats_list((self.batch_size, self.max_seq_length)					)
         else:
           # make sure that inputs increase in size
           _lowerCAmelCase    :					List[Any]							=   [
               _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:
           _lowerCAmelCase    :					str							=   [np.asarray(snake_case_					) for x in audio_inputs]

         return audio_inputs



@require_torch
class 					a_					(_a							,     unittest.TestCase      ):
       __lowerCAmelCase      :			Optional[Any]      = EncodecFeatureExtractor




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Union[str, Any]							=   EnCodecFeatureExtractionTester(self					)




       def 							__UpperCamelCase    (       self					):
         # Tests that all call wrap to encode_plus and batch_encode_plus
         _lowerCAmelCase    :					List[Any]							=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
         # create three inputs of length 800, 1000, and 1200
         _lowerCAmelCase    :					List[str]							=   [floats_list((1, x)					)[0] for x in range(8_0_0				,				1_4_0_0				,				2_0_0					)]
         _lowerCAmelCase    :					Any							=   [np.asarray(snake_case_					) for audio_input in audio_inputs]

         # Test not batched input
         _lowerCAmelCase    :					List[str]							=   feat_extract(audio_inputs[0]				,				return_tensors="""np"""					).input_values
         _lowerCAmelCase    :					Optional[int]							=   feat_extract(np_audio_inputs[0]				,				return_tensors="""np"""					).input_values
         self.assertTrue(np.allclose(snake_case_				,				snake_case_				,				atol=1E-3					)					)

         # Test batched
         _lowerCAmelCase    :					List[str]							=   feat_extract(snake_case_				,				padding=snake_case_				,				return_tensors="""np"""					).input_values
         _lowerCAmelCase    :					Dict							=   feat_extract(snake_case_				,				padding=snake_case_				,				return_tensors="""np"""					).input_values
         for enc_seq_a, enc_seq_a in zip(snake_case_				,				snake_case_					):
           self.assertTrue(np.allclose(snake_case_				,				snake_case_				,				atol=1E-3					)					)




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					str							=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
         _lowerCAmelCase    :					int							=   np.random.rand(1_0_0					).astype(np.floataa					)
         _lowerCAmelCase    :					Optional[Any]							=   np_audio_inputs.tolist()

         for inputs in [py_audio_inputs, np_audio_inputs]:
           _lowerCAmelCase    :					List[Any]							=   feature_extractor.pad([{"""input_values""": inputs}]				,				return_tensors="""np"""					)
           self.assertTrue(np_processed.input_values.dtype == np.floataa					)
           _lowerCAmelCase    :					int							=   feature_extractor.pad([{"""input_values""": inputs}]				,				return_tensors="""pt"""					)
           self.assertTrue(pt_processed.input_values.dtype == torch.floataa					)




       def 							__UpperCamelCase    (       self				,				snake_case_					):
         from datasets import load_dataset

         _lowerCAmelCase    :					List[str]							=   load_dataset("""hf-internal-testing/librispeech_asr_dummy"""				,				"""clean"""				,				split="""validation"""					)
         # automatic decoding with librispeech
         _lowerCAmelCase    :					Union[str, Any]							=   ds.sort("""id"""					).select(range(snake_case_					)					)[:num_samples]["""audio"""]

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




       def 							__UpperCamelCase    (       self					):
         # fmt: off
         _lowerCAmelCase    :					Optional[int]							=   torch.tensor(
             [2.38_04E-03, 2.07_52E-03, 1.98_36E-03, 2.10_57E-03, 1.61_74E-03,
              3.05_18E-04, 9.15_53E-05, 3.35_69E-04, 9.76_56E-04, 1.83_11E-03,
              2.01_42E-03, 2.10_57E-03, 1.73_95E-03, 4.57_76E-04, -3.96_73E-04,
              4.57_76E-04, 1.00_71E-03, 9.15_53E-05, 4.88_28E-04, 1.15_97E-03,
              7.32_42E-04, 9.46_04E-04, 1.80_05E-03, 1.83_11E-03, 8.85_01E-04,
              4.27_25E-04, 4.88_28E-04, 7.32_42E-04, 1.09_86E-03, 2.10_57E-03]					)
         # fmt: on
         _lowerCAmelCase    :					str							=   self._load_datasamples(1					)
         _lowerCAmelCase    :					Tuple							=   EncodecFeatureExtractor()
         _lowerCAmelCase    :					List[str]							=   feature_extractor(snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(input_values.shape				,				(1, 1, 9_3_6_8_0)					)
         self.assertTrue(torch.allclose(input_values[0, 0, :3_0]				,				snake_case_				,				atol=1E-6					)					)




       def 							__UpperCamelCase    (       self					):
         # fmt: off
         _lowerCAmelCase    :					Any							=   torch.tensor(
             [2.38_04E-03, 2.07_52E-03, 1.98_36E-03, 2.10_57E-03, 1.61_74E-03,
              3.05_18E-04, 9.15_53E-05, 3.35_69E-04, 9.76_56E-04, 1.83_11E-03,
              2.01_42E-03, 2.10_57E-03, 1.73_95E-03, 4.57_76E-04, -3.96_73E-04,
              4.57_76E-04, 1.00_71E-03, 9.15_53E-05, 4.88_28E-04, 1.15_97E-03,
              7.32_42E-04, 9.46_04E-04, 1.80_05E-03, 1.83_11E-03, 8.85_01E-04,
              4.27_25E-04, 4.88_28E-04, 7.32_42E-04, 1.09_86E-03, 2.10_57E-03]					)
         # fmt: on
         _lowerCAmelCase    :					Optional[Any]							=   self._load_datasamples(1					)
         _lowerCAmelCase    :					Any							=   [np.tile(input_audio[0][None]				,				reps=(2, 1)					)]
         input_audio[0][1] *= 0.5
         _lowerCAmelCase    :					Dict							=   EncodecFeatureExtractor(feature_size=2					)
         _lowerCAmelCase    :					List[Any]							=   feature_extractor(snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(input_values.shape				,				(1, 2, 9_3_6_8_0)					)
         self.assertTrue(torch.allclose(input_values[0, 0, :3_0]				,				snake_case_				,				atol=1E-6					)					)
         self.assertTrue(torch.allclose(input_values[0, 1, :3_0]				,				EXPECTED_INPUT_VALUES * 0.5				,				atol=1E-6					)					)







       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					str							=   self._load_datasamples(2					)
         # would be easier if the stride was like
         _lowerCAmelCase    :					int							=   EncodecFeatureExtractor(feature_size=1				,				chunk_length_s=1				,				overlap=0.01					)

         # pad and trunc raise an error ?
         with self.assertRaisesRegex(
             snake_case_				,				"""^Both padding and truncation were set. Make sure you only set one.$"""				,				):
           _lowerCAmelCase    :					List[str]							=   feature_extractor(
               snake_case_				,				padding="""max_length"""				,				truncation=snake_case_				,				return_tensors="""pt"""					).input_values

         # truncate to chunk
         _lowerCAmelCase    :					Any							=   feature_extractor(snake_case_				,				truncation=snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(2, 1, 7_1_5_2_0)					)  # 2 chunks

         # force truncate to max_length
         _lowerCAmelCase    :					Tuple							=   feature_extractor(
             snake_case_				,				truncation=snake_case_				,				max_length=4_8_0_0_0				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(2, 1, 4_8_0_0_0)					)

         # pad to chunk
         _lowerCAmelCase    :					Dict							=   feature_extractor(snake_case_				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(padded_outputs.shape				,				(2, 1, 9_5_2_8_0)					)

         # pad to chunk
         _lowerCAmelCase    :					Any							=   feature_extractor(snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(2, 1, 9_5_2_8_0)					)

         # force pad to max length
         _lowerCAmelCase    :					Any							=   feature_extractor(
             snake_case_				,				padding="""max_length"""				,				max_length=1_0_0_0_0_0				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(2, 1, 1_0_0_0_0_0)					)

         # force no pad
         with self.assertRaisesRegex(
             snake_case_				,				"""^Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.$"""				,				):
           _lowerCAmelCase    :					List[Any]							=   feature_extractor(snake_case_				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values

         _lowerCAmelCase    :					Any							=   feature_extractor(input_audio[0]				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(1, 1, 9_3_6_8_0)					)

         # no pad if no chunk_length_s
         _lowerCAmelCase    :					str							=   None
         with self.assertRaisesRegex(
             snake_case_				,				"""^Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.$"""				,				):
           _lowerCAmelCase    :					Union[str, Any]							=   feature_extractor(snake_case_				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values

         _lowerCAmelCase    :					Tuple							=   feature_extractor(input_audio[0]				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(1, 1, 9_3_6_8_0)					)

         # no pad if no overlap
         _lowerCAmelCase    :					Dict							=   2
         _lowerCAmelCase    :					Tuple							=   None
         with self.assertRaisesRegex(
             snake_case_				,				"""^Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.$"""				,				):
           _lowerCAmelCase    :					Optional[int]							=   feature_extractor(snake_case_				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values

         _lowerCAmelCase    :					List[Any]							=   feature_extractor(input_audio[0]				,				padding=snake_case_				,				return_tensors="""pt"""					).input_values
         self.assertEquals(truncated_outputs.shape				,				(1, 1, 9_3_6_8_0)					)




'''simple docstring'''

import unittest

import numpy as np

from transformers.testing_utils import 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 ConvNextImageProcessor


class 					a_					(unittest.TestCase      ):




       def __init__(       self				,				snake_case_				,				snake_case_=7				,				snake_case_=3				,				snake_case_=1_8				,				snake_case_=3_0				,				snake_case_=4_0_0				,				snake_case_=True				,				snake_case_=None				,				snake_case_=0.875				,				snake_case_=True				,				snake_case_=[0.5, 0.5, 0.5]				,				snake_case_=[0.5, 0.5, 0.5]				,				):
         _lowerCAmelCase    :					List[str]							=   size if size is not None else {"""shortest_edge""": 2_0}
         _lowerCAmelCase    :					Tuple							=   parent
         _lowerCAmelCase    :					List[str]							=   batch_size
         _lowerCAmelCase    :					List[str]							=   num_channels
         _lowerCAmelCase    :					Tuple							=   image_size
         _lowerCAmelCase    :					Union[str, Any]							=   min_resolution
         _lowerCAmelCase    :					Tuple							=   max_resolution
         _lowerCAmelCase    :					List[Any]							=   do_resize
         _lowerCAmelCase    :					Dict							=   size
         _lowerCAmelCase    :					str							=   crop_pct
         _lowerCAmelCase    :					List[str]							=   do_normalize
         _lowerCAmelCase    :					Any							=   image_mean
         _lowerCAmelCase    :					Any							=   image_std







       def 							__UpperCamelCase    (       self					):
         return {
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_normalize": self.do_normalize,
             "do_resize": self.do_resize,
             "size": self.size,
             "crop_pct": self.crop_pct,
         }



@require_torch
@require_vision
class 					a_					(_a							,     unittest.TestCase      ):
       __lowerCAmelCase      :			Dict      = ConvNextImageProcessor if is_vision_available() else None




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					int							=   ConvNextImageProcessingTester(self					)




       @property
       def 							__UpperCamelCase    (       self					):
         return self.image_processor_tester.prepare_image_processor_dict()




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					List[Any]							=   self.image_processing_class(**self.image_processor_dict					)
         self.assertTrue(hasattr(snake_case_				,				"""do_resize"""					)					)
         self.assertTrue(hasattr(snake_case_				,				"""size"""					)					)
         self.assertTrue(hasattr(snake_case_				,				"""crop_pct"""					)					)
         self.assertTrue(hasattr(snake_case_				,				"""do_normalize"""					)					)
         self.assertTrue(hasattr(snake_case_				,				"""image_mean"""					)					)
         self.assertTrue(hasattr(snake_case_				,				"""image_std"""					)					)




       def 							__UpperCamelCase    (       self					):
         _lowerCAmelCase    :					Any							=   self.image_processing_class.from_dict(self.image_processor_dict					)
         self.assertEqual(image_processor.size				,				{"""shortest_edge""": 2_0}					)

         _lowerCAmelCase    :					List[Any]							=   self.image_processing_class.from_dict(self.image_processor_dict				,				size=4_2					)
         self.assertEqual(image_processor.size				,				{"""shortest_edge""": 4_2}					)




       def 							__UpperCamelCase    (       self					):
         pass




       def 							__UpperCamelCase    (       self					):
         # Initialize image_processing
         _lowerCAmelCase    :					str							=   self.image_processing_class(**self.image_processor_dict					)
         # create random PIL images
         _lowerCAmelCase    :					str							=   prepare_image_inputs(self.image_processor_tester				,				equal_resolution=snake_case_					)
         for image in image_inputs:
           self.assertIsInstance(snake_case_				,				Image.Image					)

         # Test not batched input
         _lowerCAmelCase    :					Optional[int]							=   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["""shortest_edge"""],
                 self.image_processor_tester.size["""shortest_edge"""],
             )				,				)

         # Test batched
         _lowerCAmelCase    :					Optional[Any]							=   image_processing(snake_case_				,				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["""shortest_edge"""],
                 self.image_processor_tester.size["""shortest_edge"""],
             )				,				)




       def 							__UpperCamelCase    (       self					):
         # Initialize image_processing
         _lowerCAmelCase    :					int							=   self.image_processing_class(**self.image_processor_dict					)
         # create random numpy tensors
         _lowerCAmelCase    :					Any							=   prepare_image_inputs(self.image_processor_tester				,				equal_resolution=snake_case_				,				numpify=snake_case_					)
         for image in image_inputs:
           self.assertIsInstance(snake_case_				,				np.ndarray					)

         # Test not batched input
         _lowerCAmelCase    :					Optional[Any]							=   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["""shortest_edge"""],
                 self.image_processor_tester.size["""shortest_edge"""],
             )				,				)

         # Test batched
         _lowerCAmelCase    :					List[str]							=   image_processing(snake_case_				,				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["""shortest_edge"""],
                 self.image_processor_tester.size["""shortest_edge"""],
             )				,				)







       def 							__UpperCamelCase    (       self					):
         # Initialize image_processing
         _lowerCAmelCase    :					Tuple							=   self.image_processing_class(**self.image_processor_dict					)
         # create random PyTorch tensors
         _lowerCAmelCase    :					List[str]							=   prepare_image_inputs(self.image_processor_tester				,				equal_resolution=snake_case_				,				torchify=snake_case_					)
         for image in image_inputs:
           self.assertIsInstance(snake_case_				,				torch.Tensor					)

         # Test not batched input
         _lowerCAmelCase    :					List[str]							=   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["""shortest_edge"""],
                 self.image_processor_tester.size["""shortest_edge"""],
             )				,				)

         # Test batched
         _lowerCAmelCase    :					Optional[int]							=   image_processing(snake_case_				,				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["""shortest_edge"""],
                 self.image_processor_tester.size["""shortest_edge"""],
             )				,				)


