

'''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


_snake_case     						=						random.Random()







def       _A	(			snake_case	,							snake_case=1.0	,							snake_case=None	,							snake_case=None  )    ->			str:

   '''simple docstring'''





   if rng is None:
      _lowercase    :   List[str]      =     global_rng

   _lowercase    :   Tuple      =     []
   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    ,       _UpperCamelCase    ,       _UpperCamelCase=7    ,       _UpperCamelCase=400    ,       _UpperCamelCase=2000    ,       _UpperCamelCase=1    ,       _UpperCamelCase=0.0    ,       _UpperCamelCase=24000    ,       _UpperCamelCase=True    ,       ):





      """simple docstring"""





      _lowercase    :   List[str]      =     parent
      _lowercase    :   str      =     batch_size
      _lowercase    :   Optional[int]      =     min_seq_length
      _lowercase    :   List[Any]      =     max_seq_length
      _lowercase    :   Union[str, Any]      =     (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
      _lowercase    :   Any      =     feature_size
      _lowercase    :   int      =     padding_value
      _lowercase    :   List[str]      =     sampling_rate
      _lowercase    :   List[Any]      =     return_attention_mask


   def 		_lowerCamelCase     (				self						):





      """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,
      }






   def 		_lowerCamelCase     (				self    ,       _UpperCamelCase=False    ,       _UpperCamelCase=False						):





      """simple docstring"""





      def _flatten(_UpperCamelCase						):
         return list(itertools.chain(*_lowerCAmelCase						)						)

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

      return audio_inputs




@require_torch
class      a__						(							A__						,   unittest.TestCase						):
   _SCREAMING_SNAKE_CASE					:  Optional[Any]			 =							EncodecFeatureExtractor


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   int      =     EnCodecFeatureExtractionTester(self						)


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Union[str, Any]      =     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
      # create three inputs of length 800, 1000, and 1200
      _lowercase    :   List[Any]      =     [floats_list((1, x)						)[0] for x in range(800    ,       1400    ,       200						)]
      _lowercase    :   str      =     [np.asarray(_lowerCAmelCase						) for audio_input in audio_inputs]

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

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


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   List[str]      =     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
      _lowercase    :   List[str]      =     np.random.rand(100						).astype(np.floataa						)
      _lowercase    :   Dict      =     np_audio_inputs.tolist()

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


   def 		_lowerCamelCase     (				self    ,       _UpperCamelCase						):





      """simple docstring"""





      from datasets import load_dataset

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

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


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Tuple      =     torch.tensor(
          [2.3_8_0_4E-0_3, 2.0_7_5_2E-0_3, 1.9_8_3_6E-0_3, 2.1_0_5_7E-0_3, 1.6_1_7_4E-0_3,
           3.0_5_1_8E-0_4, 9.1_5_5_3E-0_5, 3.3_5_6_9E-0_4, 9.7_6_5_6E-0_4, 1.8_3_1_1E-0_3,
           2.0_1_4_2E-0_3, 2.1_0_5_7E-0_3, 1.7_3_9_5E-0_3, 4.5_7_7_6E-0_4, -3.9_6_7_3E-0_4,
           4.5_7_7_6E-0_4, 1.0_0_7_1E-0_3, 9.1_5_5_3E-0_5, 4.8_8_2_8E-0_4, 1.1_5_9_7E-0_3,
           7.3_2_4_2E-0_4, 9.4_6_0_4E-0_4, 1.8_0_0_5E-0_3, 1.8_3_1_1E-0_3, 8.8_5_0_1E-0_4,
           4.2_7_2_5E-0_4, 4.8_8_2_8E-0_4, 7.3_2_4_2E-0_4, 1.0_9_8_6E-0_3, 2.1_0_5_7E-0_3]						)
      # fmt: on
      _lowercase    :   Union[str, Any]      =     self._load_datasamples(1						)
      _lowercase    :   Tuple      =     EncodecFeatureExtractor()
      _lowercase    :   Optional[int]      =     feature_extractor(_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(input_values.shape    ,       (1, 1, 93680)						)
      self.assertTrue(torch.allclose(input_values[0, 0, :30]    ,       _lowerCAmelCase    ,       atol=1E-6						)						)


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   int      =     torch.tensor(
          [2.3_8_0_4E-0_3, 2.0_7_5_2E-0_3, 1.9_8_3_6E-0_3, 2.1_0_5_7E-0_3, 1.6_1_7_4E-0_3,
           3.0_5_1_8E-0_4, 9.1_5_5_3E-0_5, 3.3_5_6_9E-0_4, 9.7_6_5_6E-0_4, 1.8_3_1_1E-0_3,
           2.0_1_4_2E-0_3, 2.1_0_5_7E-0_3, 1.7_3_9_5E-0_3, 4.5_7_7_6E-0_4, -3.9_6_7_3E-0_4,
           4.5_7_7_6E-0_4, 1.0_0_7_1E-0_3, 9.1_5_5_3E-0_5, 4.8_8_2_8E-0_4, 1.1_5_9_7E-0_3,
           7.3_2_4_2E-0_4, 9.4_6_0_4E-0_4, 1.8_0_0_5E-0_3, 1.8_3_1_1E-0_3, 8.8_5_0_1E-0_4,
           4.2_7_2_5E-0_4, 4.8_8_2_8E-0_4, 7.3_2_4_2E-0_4, 1.0_9_8_6E-0_3, 2.1_0_5_7E-0_3]						)
      # fmt: on
      _lowercase    :   Dict      =     self._load_datasamples(1						)
      _lowercase    :   Optional[int]      =     [np.tile(input_audio[0][None]    ,       reps=(2, 1)						)]
      input_audio[0][1] *= 0.5
      _lowercase    :   int      =     EncodecFeatureExtractor(feature_size=2						)
      _lowercase    :   Optional[Any]      =     feature_extractor(_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(input_values.shape    ,       (1, 2, 93680)						)
      self.assertTrue(torch.allclose(input_values[0, 0, :30]    ,       _lowerCAmelCase    ,       atol=1E-6						)						)
      self.assertTrue(torch.allclose(input_values[0, 1, :30]    ,       EXPECTED_INPUT_VALUES * 0.5    ,       atol=1E-6						)						)






   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   str      =     self._load_datasamples(2						)
      # would be easier if the stride was like
      _lowercase    :   List[Any]      =     EncodecFeatureExtractor(feature_size=1    ,       chunk_length_s=1    ,       overlap=0.0_1						)

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

      # truncate to chunk
      _lowercase    :   List[Any]      =     feature_extractor(_lowerCAmelCase    ,       truncation=_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (2, 1, 71520)						)  # 2 chunks

      # force truncate to max_length
      _lowercase    :   Optional[int]      =     feature_extractor(
          _lowerCAmelCase    ,       truncation=_lowerCAmelCase    ,       max_length=48000    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (2, 1, 48000)						)

      # pad to chunk
      _lowercase    :   List[str]      =     feature_extractor(_lowerCAmelCase    ,       padding=_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(padded_outputs.shape    ,       (2, 1, 95280)						)

      # pad to chunk
      _lowercase    :   Optional[int]      =     feature_extractor(_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (2, 1, 95280)						)

      # force pad to max length
      _lowercase    :   Optional[int]      =     feature_extractor(
          _lowerCAmelCase    ,       padding="max_length"    ,       max_length=100000    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (2, 1, 100000)						)

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

      _lowercase    :   Optional[Any]      =     feature_extractor(input_audio[0]    ,       padding=_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (1, 1, 93680)						)

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

      _lowercase    :   int      =     feature_extractor(input_audio[0]    ,       padding=_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (1, 1, 93680)						)

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

      _lowercase    :   Optional[Any]      =     feature_extractor(input_audio[0]    ,       padding=_lowerCAmelCase    ,       return_tensors="pt"						).input_values
      self.assertEquals(truncated_outputs.shape    ,       (1, 1, 93680)						)









'''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


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import TvltImageProcessor







def       _A	(			snake_case	,							snake_case=10	,							snake_case=10	,							snake_case=False	,							snake_case=False  )    ->			List[Any]:
   _lowercase    :   Dict      =     []
   for i in range(image_processor_tester.num_frames  ):
      video.append(np.random.randint(2_55	,							size=(image_processor_tester.num_channels, width, height)	,							dtype=np.uinta  )  )

   if not numpify and not torchify:
      # PIL expects the channel dimension as last dimension
      _lowercase    :   Union[str, Any]      =     [Image.fromarray(np.moveaxis(snake_case	,							0	,							-1  )  ) for frame in video]

   if torchify:
      _lowercase    :   Any      =     [torch.from_numpy(snake_case  ) for frame in video]

   return video







def       _A	(			snake_case	,							snake_case=False	,							snake_case=False	,							snake_case=False  )    ->			Tuple:
   assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

   _lowercase    :   Optional[Any]      =     []
   for i in range(image_processor_tester.batch_size  ):
      if equal_resolution:
         _lowercase    :   List[Any]      =     image_processor_tester.max_resolution
      else:
         _lowercase  ,   _lowercase    :   Dict      =     np.random.choice(
             np.arange(image_processor_tester.min_resolution	,							image_processor_tester.max_resolution  )	,							2  )
         _lowercase    :   List[Any]      =     prepare_video(
             image_processor_tester=snake_case	,							width=snake_case	,							height=snake_case	,							numpify=snake_case	,							torchify=snake_case	,							)
      video_inputs.append(snake_case  )

   return video_inputs


class      a__						(							unittest.TestCase						):


   def __init__(				self    ,       _UpperCamelCase    ,       _UpperCamelCase=7    ,       _UpperCamelCase=3    ,       _UpperCamelCase=4    ,       _UpperCamelCase=18    ,       _UpperCamelCase=30    ,       _UpperCamelCase=400    ,       _UpperCamelCase=True    ,       _UpperCamelCase=None    ,       _UpperCamelCase=True    ,       _UpperCamelCase=[0.5, 0.5, 0.5]    ,       _UpperCamelCase=[0.5, 0.5, 0.5]    ,       _UpperCamelCase=True    ,       _UpperCamelCase=None    ,       ):





      """simple docstring"""





      _lowercase    :   List[str]      =     size if size is not None else {"shortest_edge": 18}
      _lowercase    :   Any      =     crop_size if crop_size is not None else {"height": 18, "width": 18}

      _lowercase    :   Dict      =     parent
      _lowercase    :   Optional[Any]      =     batch_size
      _lowercase    :   List[Any]      =     num_channels
      _lowercase    :   Optional[Any]      =     num_frames
      _lowercase    :   int      =     image_size
      _lowercase    :   Optional[int]      =     min_resolution
      _lowercase    :   Optional[int]      =     max_resolution
      _lowercase    :   Optional[Any]      =     do_resize
      _lowercase    :   Dict      =     size
      _lowercase    :   Any      =     do_normalize
      _lowercase    :   Tuple      =     image_mean
      _lowercase    :   Union[str, Any]      =     image_std
      _lowercase    :   Tuple      =     do_center_crop
      _lowercase    :   str      =     crop_size






   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
      }




@require_torch
@require_vision
class      a__						(							lowerCamelCase_						,   unittest.TestCase						):
   _SCREAMING_SNAKE_CASE					:  List[str]			 =							TvltImageProcessor if is_vision_available() else None


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Optional[Any]      =     TvltImageProcessorTester(self						)


   @property
   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      return self.image_processor_tester.prepare_image_processor_dict()


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   int      =     self.image_processing_class(**self.image_processor_dict						)
      self.assertTrue(hasattr(_UpperCamelCase    ,       "image_mean"						)						)
      self.assertTrue(hasattr(_UpperCamelCase    ,       "image_std"						)						)
      self.assertTrue(hasattr(_UpperCamelCase    ,       "do_normalize"						)						)
      self.assertTrue(hasattr(_UpperCamelCase    ,       "do_resize"						)						)
      self.assertTrue(hasattr(_UpperCamelCase    ,       "do_center_crop"						)						)
      self.assertTrue(hasattr(_UpperCamelCase    ,       "size"						)						)


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Any      =     self.image_processing_class(**self.image_processor_dict						)
      # create random PIL videos
      _lowercase    :   Any      =     prepare_video_inputs(self.image_processor_tester    ,       equal_resolution=_UpperCamelCase						)
      for video in video_inputs:
         self.assertIsInstance(_UpperCamelCase    ,       _UpperCamelCase						)
         self.assertIsInstance(video[0]    ,       Image.Image						)

      # Test not batched input
      _lowercase    :   Any      =     image_processor(video_inputs[0]    ,       return_tensors="pt"						).pixel_values
      self.assertEqual(
          encoded_videos.shape    ,       (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )    ,       )

      # Test batched
      _lowercase    :   Union[str, Any]      =     image_processor(_UpperCamelCase    ,       return_tensors="pt"						).pixel_values
      self.assertEqual(
          encoded_videos.shape    ,       (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )    ,       )


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Optional[Any]      =     self.image_processing_class(**self.image_processor_dict						)
      # create random numpy tensors
      _lowercase    :   List[str]      =     prepare_video_inputs(self.image_processor_tester    ,       equal_resolution=_UpperCamelCase    ,       numpify=_UpperCamelCase						)
      for video in video_inputs:
         self.assertIsInstance(_UpperCamelCase    ,       _UpperCamelCase						)
         self.assertIsInstance(video[0]    ,       np.ndarray						)

      # Test not batched input
      _lowercase    :   Optional[int]      =     image_processor(video_inputs[0]    ,       return_tensors="pt"						).pixel_values
      self.assertEqual(
          encoded_videos.shape    ,       (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )    ,       )

      # Test batched
      _lowercase    :   List[Any]      =     image_processor(_UpperCamelCase    ,       return_tensors="pt"						).pixel_values
      self.assertEqual(
          encoded_videos.shape    ,       (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )    ,       )






   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Dict      =     self.image_processing_class(**self.image_processor_dict						)
      # create random PyTorch tensors
      _lowercase    :   Optional[int]      =     prepare_video_inputs(self.image_processor_tester    ,       equal_resolution=_UpperCamelCase    ,       torchify=_UpperCamelCase						)
      for video in video_inputs:
         self.assertIsInstance(_UpperCamelCase    ,       _UpperCamelCase						)
         self.assertIsInstance(video[0]    ,       torch.Tensor						)

      # Test not batched input
      _lowercase    :   int      =     image_processor(video_inputs[0]    ,       return_tensors="pt"						).pixel_values
      self.assertEqual(
          encoded_videos.shape    ,       (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )    ,       )

      # Test batched
      _lowercase    :   List[Any]      =     image_processor(_UpperCamelCase    ,       return_tensors="pt"						).pixel_values
      self.assertEqual(
          encoded_videos.shape    ,       (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )    ,       )






