





'''simple docstring'''







import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_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_speech_available():
   from transformers import WhisperFeatureExtractor

if is_torch_available():
   import torch

_lowercase       						=			random.Random()

def    __UpperCamelCase	(	a    : List[Any]					,   a    : int=1.0					,   a    : Dict=None					,   a    : str=None     ) ->Optional[int]:
 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
@require_torch
@require_torchaudio
class 			_lowercase						(       unittest.TestCase					):







     def __init__( self    ,   A__    ,   A__=7    ,   A__=4_00    ,   A__=20_00    ,   A__=10    ,   A__=1_60    ,   A__=8    ,   A__=0.0    ,   A__=40_00    ,   A__=False    ,   A__=True    ,   ) ->	Union[str, Any]:
      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				=			padding_value
      snake_case				=			sampling_rate
      snake_case				=			return_attention_mask
      snake_case				=			do_normalize
      snake_case				=			feature_size
      snake_case				=			chunk_length
      snake_case				=			hop_length







     def     UpperCamelCase			( self    ) ->	Tuple:
      return {
          "feature_size": self.feature_size,
          "hop_length": self.hop_length,
          "chunk_length": self.chunk_length,
          "padding_value": self.padding_value,
          "sampling_rate": self.sampling_rate,
          "return_attention_mask": self.return_attention_mask,
          "do_normalize": self.do_normalize,
      }







     def     UpperCamelCase			( self    ,   A__=False    ,   A__=False    ) ->	List[Any]:
      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 			_lowercase						(       __a				,		unittest.TestCase					):
     _UpperCAmelCase										=					WhisperFeatureExtractor if is_speech_available() else None







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      snake_case				=			WhisperFeatureExtractionTester(self    )







     def     UpperCamelCase			( self    ) ->	Any:
      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				=			feat_extract_first.mel_filters
      snake_case				=			feat_extract_second.mel_filters
      self.assertTrue(np.allclose(A__    ,   A__    )    )
      self.assertEqual(A__    ,   A__    )







     def     UpperCamelCase			( self    ) ->	str:
      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				=			feat_extract_first.mel_filters
      snake_case				=			feat_extract_second.mel_filters
      self.assertTrue(np.allclose(A__    ,   A__    )    )
      self.assertEqual(A__    ,   A__    )







     def     UpperCamelCase			( self    ) ->	List[str]:
      # Tests that all call wrap to encode_plus and batch_encode_plus
      snake_case				=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
      # create three inputs of length 800, 1000, and 1200
      snake_case				=			[floats_list((1, x)    )[0] for x in range(8_00    ,   14_00    ,   2_00    )]
      snake_case				=			[np.asarray(A__    ) for speech_input in speech_inputs]

      # Test feature size
      snake_case				=			feature_extractor(A__    ,   padding='''max_length'''    ,   return_tensors='''np'''    ).input_features
      self.assertTrue(input_features.ndim == 3    )
      self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames    )
      self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size    )

      # Test not batched input
      snake_case				=			feature_extractor(speech_inputs[0]    ,   return_tensors='''np'''    ).input_features
      snake_case				=			feature_extractor(np_speech_inputs[0]    ,   return_tensors='''np'''    ).input_features
      self.assertTrue(np.allclose(A__    ,   A__    ,   atol=1e-3    )    )

      # Test batched
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      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.
      snake_case				=			[floats_list((1, x)    )[0] for x in (8_00, 8_00, 8_00)]
      snake_case				=			np.asarray(A__    )
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      for enc_seq_a, enc_seq_a in zip(A__    ,   A__    ):
       self.assertTrue(np.allclose(A__    ,   A__    ,   atol=1e-3    )    )

      # Test truncation required
      snake_case				=			[floats_list((1, x)    )[0] for x in range(2_00    ,   (feature_extractor.n_samples + 5_00)    ,   2_00    )]
      snake_case				=			[np.asarray(A__    ) for speech_input in speech_inputs]

      snake_case				=			[x[: feature_extractor.n_samples] for x in speech_inputs]
      snake_case				=			[np.asarray(A__    ) for speech_input in speech_inputs_truncated]

      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      for enc_seq_a, enc_seq_a in zip(A__    ,   A__    ):
       self.assertTrue(np.allclose(A__    ,   A__    ,   atol=1e-3    )    )







     def     UpperCamelCase			( self    ) ->	List[Any]:
      import torch

      snake_case				=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
      snake_case				=			np.random.rand(1_00    ,   32    ).astype(np.floataa    )
      snake_case				=			np_speech_inputs.tolist()

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







     def     UpperCamelCase			( self    ,   A__    ) ->	Union[str, Any]:
      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     UpperCamelCase			( self    ) ->	List[str]:
      # fmt: off
      snake_case				=			torch.tensor(
          [
              0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
              0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
              0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
              -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
          ]    )
      # fmt: on

      snake_case				=			self._load_datasamples(1    )
      snake_case				=			WhisperFeatureExtractor()
      snake_case				=			feature_extractor(A__    ,   return_tensors='''pt'''    ).input_features
      self.assertEqual(input_features.shape    ,   (1, 80, 30_00)    )
      self.assertTrue(torch.allclose(input_features[0, 0, :30]    ,   A__    ,   atol=1e-4    )    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      snake_case				=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
      snake_case				=			self._load_datasamples(1    )[0]
      snake_case				=			((audio - audio.min()) / (audio.max() - audio.min())) * 6_55_35  # Rescale to [0, 65535] to show issue
      snake_case				=			feat_extract.zero_mean_unit_var_norm([audio]    ,   attention_mask=A__    )[0]

      self.assertTrue(np.all(np.mean(A__    ) < 1e-3    )    )
      self.assertTrue(np.all(np.abs(np.var(A__    ) - 1    ) < 1e-3    )    )








'''simple docstring'''







import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 			_lowercase						(       __a				,		__a				,		unittest.TestCase					):
     _UpperCAmelCase										=					IFInpaintingSuperResolutionPipeline
     _UpperCAmelCase										=					TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''}
     _UpperCAmelCase										=					TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'''original_image'''}					)
     _UpperCAmelCase										=					PipelineTesterMixin.required_optional_params - {'''latents'''}







     def     UpperCamelCase			( self    ) ->	int:
      return self._get_superresolution_dummy_components()







     def     UpperCamelCase			( self    ,   A__    ,   A__=0    ) ->	Union[str, Any]:
      if str(A__    ).startswith('''mps'''    ):
       snake_case				=			torch.manual_seed(A__    )
      else:
       snake_case				=			torch.Generator(device=A__    ).manual_seed(A__    )

      snake_case				=			floats_tensor((1, 3, 16, 16)    ,   rng=random.Random(A__    )    ).to(A__    )
      snake_case				=			floats_tensor((1, 3, 32, 32)    ,   rng=random.Random(A__    )    ).to(A__    )
      snake_case				=			floats_tensor((1, 3, 32, 32)    ,   rng=random.Random(A__    )    ).to(A__    )

      snake_case				=			{
          '''prompt''': '''A painting of a squirrel eating a burger''',
          '''image''': image,
          '''original_image''': original_image,
          '''mask_image''': mask_image,
          '''generator''': generator,
          '''num_inference_steps''': 2,
          '''output_type''': '''numpy''',
      }

      return inputs







     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()    ,   reason='''XFormers attention is only available with CUDA and `xformers` installed'''    ,   )
     def     UpperCamelCase			( self    ) ->	List[Any]:
      self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      self._test_save_load_optional_components()







     @unittest.skipIf(torch_device != '''cuda'''    ,   reason='''float16 requires CUDA'''    )
     def     UpperCamelCase			( self    ) ->	List[str]:
      # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
      super().test_save_load_floataa(expected_max_diff=1e-1    )







     def     UpperCamelCase			( self    ) ->	int:
      self._test_attention_slicing_forward_pass(expected_max_diff=1e-2    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      self._test_save_load_local()







     def     UpperCamelCase			( self    ) ->	Dict:
      self._test_inference_batch_single_identical(
          expected_max_diff=1e-2    ,   )

