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


_A     :			List[str]  						=			random.Random()

if is_torch_available():
   import torch


def     __magic_name__      ( __snake_case							:			Optional[Any]	,					__snake_case							:			Optional[int]=1.0	,					__snake_case							:			int=None	,					__snake_case							:			Tuple=None    )					->							List[Any]:
       if rng is None:
              lowercase       :							List[str]									=				global_rng

       lowercase       :							Union[str, Any]									=				[]
       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		):
   def __init__(     self      ,       _a      ,       _a=7      ,       _a=400      ,       _a=2_000      ,       _a=1      ,       _a=0.0      ,       _a=16_000      ,       _a=True      ,       _a=True      ,       ):
          lowercase       :							str									=				parent
          lowercase       :							Dict									=				batch_size
          lowercase       :							Any									=				min_seq_length
          lowercase       :							Dict									=				max_seq_length
          lowercase       :							List[str]									=				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
          lowercase       :							List[str]									=				feature_size
          lowercase       :							Any									=				padding_value
          lowercase       :							Optional[Any]									=				sampling_rate
          lowercase       :							str									=				return_attention_mask
          lowercase       :							Optional[int]									=				do_normalize
   def      __magic_name__     (     self							):
          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      __magic_name__     (     self      ,       _a=False      ,       _a=False							):
          def _flatten(_a							):
                 return list(itertools.chain(*_a							)							)

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

          return speech_inputs


@require_torch
@require_torchaudio
class 						a__		( a_,     unittest.TestCase		):
   __lowerCAmelCase				=							ASTFeatureExtractor
   def      __magic_name__     (     self							):
          lowercase       :							Any									=				ASTFeatureExtractionTester(self							)
   def      __magic_name__     (     self							):
          # Tests that all call wrap to encode_plus and batch_encode_plus
          lowercase       :							str									=				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
          # create three inputs of length 800, 1000, and 1200
          lowercase       :							Tuple									=				[floats_list((1, x)							)[0] for x in range(800      ,       1_400      ,       200							)]
          lowercase       :							List[str]									=				[np.asarray(_a							) for speech_input in speech_inputs]

          # Test not batched input
          lowercase       :							List[str]									=				feat_extract(speech_inputs[0]      ,       return_tensors="np"							).input_values
          lowercase       :							Optional[Any]									=				feat_extract(np_speech_inputs[0]      ,       return_tensors="np"							).input_values
          self.assertTrue(np.allclose(_a      ,       _a      ,       atol=1E-3							)							)

          # Test batched
          lowercase       :							Any									=				feat_extract(_a      ,       padding=_a      ,       return_tensors="np"							).input_values
          lowercase       :							List[Any]									=				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.
          lowercase       :							List[Any]									=				[floats_list((1, x)							)[0] for x in (800, 800, 800)]
          lowercase       :							Union[str, Any]									=				np.asarray(_a							)
          lowercase       :							Optional[Any]									=				feat_extract(_a      ,       return_tensors="np"							).input_values
          lowercase       :							List[str]									=				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      __magic_name__     (     self							):
          import torch

          lowercase       :							List[Any]									=				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
          lowercase       :							Tuple									=				np.random.rand(100							).astype(np.floataa							)
          lowercase       :							Optional[Any]									=				np_speech_inputs.tolist()

          for inputs in [py_speech_inputs, np_speech_inputs]:
                 lowercase       :							int									=				feature_extractor.pad([{"input_values": inputs}]      ,       return_tensors="np"							)
                 self.assertTrue(np_processed.input_values.dtype == np.floataa							)
                 lowercase       :							Optional[int]									=				feature_extractor.pad([{"input_values": inputs}]      ,       return_tensors="pt"							)
                 self.assertTrue(pt_processed.input_values.dtype == torch.floataa							)
   def      __magic_name__     (     self      ,       _a							):
          from datasets import load_dataset

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

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

   @require_torch
   def      __magic_name__     (     self							):
          # fmt: off
          lowercase       :							Tuple									=				torch.tensor(
              [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
               -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
               -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
               -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]							)
          # fmt: on

          lowercase       :							Dict									=				self._load_datasamples(1							)
          lowercase       :							Any									=				ASTFeatureExtractor()
          lowercase       :							Optional[int]									=				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
import torch

from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()

class 						a__		( unittest.TestCase		):
   @property
   def      __magic_name__     (     self							):
          torch.manual_seed(0							)
          lowercase       :							str									=				UNetaDModel(
              block_out_channels=(32, 64)      ,       layers_per_block=2      ,       sample_size=32      ,       in_channels=3      ,       out_channels=3      ,       down_block_types=("DownBlock2D", "AttnDownBlock2D")      ,       up_block_types=("AttnUpBlock2D", "UpBlock2D")      ,       )
          return model

   def      __magic_name__     (     self							):
          lowercase       :							List[str]									=				self.dummy_uncond_unet
          lowercase       :							Dict									=				KarrasVeScheduler()

          lowercase       :							Any									=				KarrasVePipeline(unet=_a      ,       scheduler=_a							)
          pipe.to(_a							)
          pipe.set_progress_bar_config(disable=_a							)

          lowercase       :							Tuple									=				torch.manual_seed(0							)
          lowercase       :							Tuple									=				pipe(num_inference_steps=2      ,       generator=_a      ,       output_type="numpy"							).images

          lowercase       :							int									=				torch.manual_seed(0							)
          lowercase       :							Tuple									=				pipe(num_inference_steps=2      ,       generator=_a      ,       output_type="numpy"      ,       return_dict=_a							)[0]

          lowercase       :							Any									=				image[0, -3:, -3:, -1]
          lowercase       :							Dict									=				image_from_tuple[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          lowercase       :							Tuple									=				np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]							)

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


@slow
@require_torch
class 						a__		( unittest.TestCase		):
   def      __magic_name__     (     self							):
          lowercase       :							Tuple									=				"google/ncsnpp-celebahq-256"
          lowercase       :							str									=				UNetaDModel.from_pretrained(_a							)
          lowercase       :							Optional[Any]									=				KarrasVeScheduler()

          lowercase       :							Union[str, Any]									=				KarrasVePipeline(unet=_a      ,       scheduler=_a							)
          pipe.to(_a							)
          pipe.set_progress_bar_config(disable=_a							)

          lowercase       :							Tuple									=				torch.manual_seed(0							)
          lowercase       :							Dict									=				pipe(num_inference_steps=20      ,       generator=_a      ,       output_type="numpy"							).images

          lowercase       :							Optional[Any]									=				image[0, -3:, -3:, -1]
          assert image.shape == (1, 256, 256, 3)
          lowercase       :							Optional[Any]									=				np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6]							)

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


