




'''simple docstring'''





import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
  import torch

if is_datasets_available():
  from datasets import load_dataset

_SCREAMING_SNAKE_CASE							:       int						=			random.Random()


def 					UpperCamelCase_(     snake_case							:	Optional[Any]							,    snake_case							:	int=1.0							,    snake_case							:	Optional[int]=None							,    snake_case							:	List[Any]=None					):

       '''simple docstring'''






       if rng is None:
              snake_case_      =				global_rng

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

       return values




class 			_snake_case		(     unittest.TestCase							):




   def __init__( self    ,							a__    ,							a__=7    ,							a__=400    ,							a__=2_000    ,							a__=2_048    ,							a__=128    ,							a__=1    ,							a__=512    ,							a__=30    ,							a__=44_100    ,							)    ->    str:

          '''simple docstring'''




          snake_case_      =				parent
          snake_case_      =				batch_size
          snake_case_      =				min_seq_length
          snake_case_      =				max_seq_length
          snake_case_      =				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
          snake_case_      =				spectrogram_length
          snake_case_      =				feature_size
          snake_case_      =				num_audio_channels
          snake_case_      =				hop_length
          snake_case_      =				chunk_length
          snake_case_      =				sampling_rate




   def        lowerCAmelCase__    ( self							)    ->    int:

          '''simple docstring'''




          return {
              "spectrogram_length": self.spectrogram_length,
              "feature_size": self.feature_size,
              "num_audio_channels": self.num_audio_channels,
              "hop_length": self.hop_length,
              "chunk_length": self.chunk_length,
              "sampling_rate": self.sampling_rate,
          }




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

          '''simple docstring'''




          def _flatten(a__							):
                 return list(itertools.chain(*A_							)							)

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




@require_torch
@require_torchaudio
class 			_snake_case		(     _SCREAMING_SNAKE_CASE						,						unittest.TestCase							):
   lowerCAmelCase_					:				Any							=   TvltFeatureExtractor




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

          '''simple docstring'''




          snake_case_      =				TvltFeatureExtractionTester(self							)




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

          '''simple docstring'''




          snake_case_      =				self.feature_extraction_class(**self.feat_extract_dict							)
          self.assertTrue(hasattr(A_    ,							"spectrogram_length"							)							)
          self.assertTrue(hasattr(A_    ,							"feature_size"							)							)
          self.assertTrue(hasattr(A_    ,							"num_audio_channels"							)							)
          self.assertTrue(hasattr(A_    ,							"hop_length"							)							)
          self.assertTrue(hasattr(A_    ,							"chunk_length"							)							)
          self.assertTrue(hasattr(A_    ,							"sampling_rate"							)							)




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

          '''simple docstring'''




          snake_case_      =				self.feature_extraction_class(**self.feat_extract_dict							)

          with tempfile.TemporaryDirectory() as tmpdirname:
                 snake_case_      =				feat_extract_first.save_pretrained(A_							)[0]
                 check_json_file_has_correct_format(A_							)
                 snake_case_      =				self.feature_extraction_class.from_pretrained(A_							)

          snake_case_      =				feat_extract_first.to_dict()
          snake_case_      =				feat_extract_second.to_dict()
          snake_case_      =				dict_first.pop("mel_filters"							)
          snake_case_      =				dict_second.pop("mel_filters"							)
          self.assertTrue(np.allclose(A_    ,							A_							)							)
          self.assertEqual(A_    ,							A_							)




   def        lowerCAmelCase__    ( self							)    ->    List[Any]:

          '''simple docstring'''




          snake_case_      =				self.feature_extraction_class(**self.feat_extract_dict							)

          with tempfile.TemporaryDirectory() as tmpdirname:
                 snake_case_      =				os.path.join(A_    ,							"feat_extract.json"							)
                 feat_extract_first.to_json_file(A_							)
                 snake_case_      =				self.feature_extraction_class.from_json_file(A_							)

          snake_case_      =				feat_extract_first.to_dict()
          snake_case_      =				feat_extract_second.to_dict()
          snake_case_      =				dict_first.pop("mel_filters"							)
          snake_case_      =				dict_second.pop("mel_filters"							)
          self.assertTrue(np.allclose(A_    ,							A_							)							)
          self.assertEqual(A_    ,							A_							)




   def        lowerCAmelCase__    ( self							)    ->    Union[str, Any]:

          '''simple docstring'''




          snake_case_      =				self.feature_extraction_class(**self.feat_extract_dict							)

          # create three inputs of length 800, 1000, and 1200
          snake_case_      =				[floats_list((1, x)							)[0] for x in range(800    ,							1_400    ,							200							)]
          snake_case_      =				[np.asarray(A_							) for speech_input in speech_inputs]

          # Test not batched input
          snake_case_      =				feature_extractor(np_speech_inputs[0]    ,							return_tensors="np"    ,							sampling_rate=44_100							).audio_values

          self.assertTrue(encoded_audios.ndim == 4							)
          self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
          self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
          self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)

          # Test batched
          snake_case_      =				feature_extractor(A_    ,							return_tensors="np"    ,							sampling_rate=44_100							).audio_values

          self.assertTrue(encoded_audios.ndim == 4							)
          self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
          self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
          self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)

          # Test audio masking
          snake_case_      =				feature_extractor(
              A_    ,							return_tensors="np"    ,							sampling_rate=44_100    ,							mask_audio=A_							).audio_values

          self.assertTrue(encoded_audios.ndim == 4							)
          self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
          self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
          self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)

          # Test 2-D numpy arrays are batched.
          snake_case_      =				[floats_list((1, x)							)[0] for x in (800, 800, 800)]
          snake_case_      =				np.asarray(A_							)
          snake_case_      =				feature_extractor(A_    ,							return_tensors="np"    ,							sampling_rate=44_100							).audio_values
          self.assertTrue(encoded_audios.ndim == 4							)
          self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size							)
          self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length							)
          self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels							)




   def        lowerCAmelCase__    ( self    ,							a__							)    ->    Optional[int]:

          '''simple docstring'''




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

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




   def        lowerCAmelCase__    ( self							)    ->    Optional[Any]:

          '''simple docstring'''




          snake_case_      =				self._load_datasamples(1							)
          snake_case_      =				TvltFeatureExtractor()
          snake_case_      =				feature_extractor(A_    ,							return_tensors="pt"							).audio_values

          self.assertEquals(audio_values.shape    ,							(1, 1, 192, 128)							)

          snake_case_      =				torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]]							)
          self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]    ,							A_    ,							atol=1e-4							)							)










'''simple docstring'''





import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


_SCREAMING_SNAKE_CASE							:       Any						=			False




class 			_snake_case		(     unittest.TestCase							):
			pass




@slow
@require_torch_gpu
class 			_snake_case		(     unittest.TestCase							):




			def        lowerCAmelCase__    ( self							)    ->    List[Any]:

										'''simple docstring'''




										snake_case_      =				VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion"							)
										pipe.to(a__							)
										pipe.set_progress_bar_config(disable=a__							)

										snake_case_      =				load_image(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"							)
										snake_case_      =				torch.manual_seed(0							)
										snake_case_      =				pipe(
										    image=a__    ,							generator=a__    ,							guidance_scale=7.5    ,							num_inference_steps=50    ,							output_type="numpy"    ,							).images

										snake_case_      =				image[0, 253:256, 253:256, -1]

										assert image.shape == (1, 512, 512, 3)
										snake_case_      =				np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5]							)

										assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2




