



import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


__UpperCAmelCase			  =			get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
__UpperCAmelCase			  =			get_tests_dir('''fixtures/vocab.json''')
__UpperCAmelCase			  =			get_tests_dir('''fixtures''')



class 							lowerCAmelCase_						(    unittest.TestCase				):
       UpperCAmelCase__							:   str  	=    ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
       def    snake_case_			(     self			)	->						Optional[Any]:
          UpperCamelCase       :    Optional[Any]		      =      0
       def    snake_case_			(     self			)	->						Union[str, Any]:
          UpperCamelCase       :    str		      =      AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h'			)
          self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)
       def    snake_case_			(     self			)	->						List[Any]:




          with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCamelCase       :    str		      =      WavaVecaConfig()
             UpperCamelCase       :    Dict		      =      AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h'			)

             # save in new folder
             model_config.save_pretrained(__lowerCamelCase			)
             processor.save_pretrained(__lowerCamelCase			)

             UpperCamelCase       :    List[str]		      =      AutoProcessor.from_pretrained(__lowerCamelCase			)

          self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)
       def    snake_case_			(     self			)	->						Optional[int]:




          with tempfile.TemporaryDirectory() as tmpdirname:
             # copy relevant files
             copyfile(__lowerCamelCase,     os.path.join(__lowerCamelCase,     __lowerCamelCase			)			)
             copyfile(__lowerCamelCase,     os.path.join(__lowerCamelCase,     'vocab.json'			)			)

             UpperCamelCase       :    Union[str, Any]		      =      AutoProcessor.from_pretrained(__lowerCamelCase			)

          self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)
       def    snake_case_			(     self			)	->						List[Any]:




          with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCamelCase       :    Union[str, Any]		      =      WavaVecaFeatureExtractor()
             UpperCamelCase       :    Optional[Any]		      =      AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h'			)

             UpperCamelCase       :    Union[str, Any]		      =      WavaVecaProcessor(__lowerCamelCase,     __lowerCamelCase			)

             # save in new folder
             processor.save_pretrained(__lowerCamelCase			)

             # drop `processor_class` in tokenizer
             with open(os.path.join(__lowerCamelCase,     __lowerCamelCase			),     'r'			) as f:
                UpperCamelCase       :    Optional[int]		      =      json.load(__lowerCamelCase			)
                config_dict.pop('processor_class'			)

             with open(os.path.join(__lowerCamelCase,     __lowerCamelCase			),     'w'			) as f:
                f.write(json.dumps(__lowerCamelCase			)			)

             UpperCamelCase       :    Tuple		      =      AutoProcessor.from_pretrained(__lowerCamelCase			)

          self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)
       def    snake_case_			(     self			)	->						Optional[int]:




          with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCamelCase       :    Optional[int]		      =      WavaVecaFeatureExtractor()
             UpperCamelCase       :    List[str]		      =      AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h'			)

             UpperCamelCase       :    List[Any]		      =      WavaVecaProcessor(__lowerCamelCase,     __lowerCamelCase			)

             # save in new folder
             processor.save_pretrained(__lowerCamelCase			)

             # drop `processor_class` in feature extractor
             with open(os.path.join(__lowerCamelCase,     __lowerCamelCase			),     'r'			) as f:
                UpperCamelCase       :    int		      =      json.load(__lowerCamelCase			)
                config_dict.pop('processor_class'			)

             with open(os.path.join(__lowerCamelCase,     __lowerCamelCase			),     'w'			) as f:
                f.write(json.dumps(__lowerCamelCase			)			)

             UpperCamelCase       :    Optional[int]		      =      AutoProcessor.from_pretrained(__lowerCamelCase			)

          self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)
       def    snake_case_			(     self			)	->						Dict:




          with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCamelCase       :    Optional[Any]		      =      WavaVecaConfig(processor_class='Wav2Vec2Processor'			)
             model_config.save_pretrained(__lowerCamelCase			)
             # copy relevant files
             copyfile(__lowerCamelCase,     os.path.join(__lowerCamelCase,     'vocab.json'			)			)
             # create emtpy sample processor
             with open(os.path.join(__lowerCamelCase,     __lowerCamelCase			),     'w'			) as f:
                f.write('{}'			)

             UpperCamelCase       :    Union[str, Any]		      =      AutoProcessor.from_pretrained(__lowerCamelCase			)

          self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)
       def    snake_case_			(     self			)	->						int:




          with self.assertRaises(__lowerCamelCase			):
             UpperCamelCase       :    Union[str, Any]		      =      AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'			)
          # If remote code is disabled, we can't load this config.
          with self.assertRaises(__lowerCamelCase			):
             UpperCamelCase       :    Dict		      =      AutoProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_processor',     trust_remote_code=__lowerCamelCase			)

          UpperCamelCase       :    List[Any]		      =      AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor',     trust_remote_code=__lowerCamelCase			)
          self.assertTrue(processor.special_attribute_present			)
          self.assertEqual(processor.__class__.__name__,     'NewProcessor'			)

          UpperCamelCase       :    Union[str, Any]		      =      processor.feature_extractor
          self.assertTrue(feature_extractor.special_attribute_present			)
          self.assertEqual(feature_extractor.__class__.__name__,     'NewFeatureExtractor'			)

          UpperCamelCase       :    Optional[int]		      =      processor.tokenizer
          self.assertTrue(tokenizer.special_attribute_present			)
          if is_tokenizers_available():
             self.assertEqual(tokenizer.__class__.__name__,     'NewTokenizerFast'			)

             # Test we can also load the slow version
             UpperCamelCase       :    int		      =      AutoProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_processor',     trust_remote_code=__lowerCamelCase,     use_fast=__lowerCamelCase			)
             UpperCamelCase       :    Optional[int]		      =      new_processor.tokenizer
             self.assertTrue(new_tokenizer.special_attribute_present			)
             self.assertEqual(new_tokenizer.__class__.__name__,     'NewTokenizer'			)
          else:
             self.assertEqual(tokenizer.__class__.__name__,     'NewTokenizer'			)
       def    snake_case_			(     self			)	->						str:




          try:
             AutoConfig.register('custom',     __lowerCamelCase			)
             AutoFeatureExtractor.register(__lowerCamelCase,     __lowerCamelCase			)
             AutoTokenizer.register(__lowerCamelCase,     slow_tokenizer_class=__lowerCamelCase			)
             AutoProcessor.register(__lowerCamelCase,     __lowerCamelCase			)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(__lowerCamelCase			):
                AutoProcessor.register(__lowerCamelCase,     __lowerCamelCase			)

             # Now that the config is registered, it can be used as any other config with the auto-API
             UpperCamelCase       :    str		      =      CustomFeatureExtractor.from_pretrained(__lowerCamelCase			)

             with tempfile.TemporaryDirectory() as tmp_dir:
                UpperCamelCase       :    Optional[Any]		      =      os.path.join(__lowerCamelCase,     'vocab.txt'			)
                with open(__lowerCamelCase,     'w',     encoding='utf-8'			) as vocab_writer:
                   vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]			)			)
                UpperCamelCase       :    Dict		      =      CustomTokenizer(__lowerCamelCase			)

             UpperCamelCase       :    Optional[Any]		      =      CustomProcessor(__lowerCamelCase,     __lowerCamelCase			)

             with tempfile.TemporaryDirectory() as tmp_dir:
                processor.save_pretrained(__lowerCamelCase			)
                UpperCamelCase       :    List[str]		      =      AutoProcessor.from_pretrained(__lowerCamelCase			)
                self.assertIsInstance(__lowerCamelCase,     __lowerCamelCase			)

          finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
             if CustomConfig in TOKENIZER_MAPPING._extra_content:
                del TOKENIZER_MAPPING._extra_content[CustomConfig]
             if CustomConfig in PROCESSOR_MAPPING._extra_content:
                del PROCESSOR_MAPPING._extra_content[CustomConfig]
       def    snake_case_			(     self			)	->						List[str]:



          class 							lowerCAmelCase_						(    SCREAMING_SNAKE_CASE__				):
                 UpperCAmelCase__							:   Optional[int]  	=    False






          class 							lowerCAmelCase_						(    SCREAMING_SNAKE_CASE__				):
                 UpperCAmelCase__							:   Union[str, Any]  	=    False






          class 							lowerCAmelCase_						(    SCREAMING_SNAKE_CASE__				):
                 UpperCAmelCase__							:   Dict  	=    "AutoFeatureExtractor"
                 UpperCAmelCase__							:   int  	=    "AutoTokenizer"
                 UpperCAmelCase__							:   Optional[Any]  	=    False

          try:
             AutoConfig.register('custom',     __lowerCamelCase			)
             AutoFeatureExtractor.register(__lowerCamelCase,     __lowerCamelCase			)
             AutoTokenizer.register(__lowerCamelCase,     slow_tokenizer_class=__lowerCamelCase			)
             AutoProcessor.register(__lowerCamelCase,     __lowerCamelCase			)
             # If remote code is not set, the default is to use local classes.
             UpperCamelCase       :    Union[str, Any]		      =      AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'			)
             self.assertEqual(processor.__class__.__name__,     'NewProcessor'			)
             self.assertFalse(processor.special_attribute_present			)
             self.assertFalse(processor.feature_extractor.special_attribute_present			)
             self.assertFalse(processor.tokenizer.special_attribute_present			)

             # If remote code is disabled, we load the local ones.
             UpperCamelCase       :    int		      =      AutoProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_processor',     trust_remote_code=__lowerCamelCase			)
             self.assertEqual(processor.__class__.__name__,     'NewProcessor'			)
             self.assertFalse(processor.special_attribute_present			)
             self.assertFalse(processor.feature_extractor.special_attribute_present			)
             self.assertFalse(processor.tokenizer.special_attribute_present			)

             # If remote is enabled, we load from the Hub.
             UpperCamelCase       :    str		      =      AutoProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_processor',     trust_remote_code=__lowerCamelCase			)
             self.assertEqual(processor.__class__.__name__,     'NewProcessor'			)
             self.assertTrue(processor.special_attribute_present			)
             self.assertTrue(processor.feature_extractor.special_attribute_present			)
             self.assertTrue(processor.tokenizer.special_attribute_present			)

          finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
             if CustomConfig in TOKENIZER_MAPPING._extra_content:
                del TOKENIZER_MAPPING._extra_content[CustomConfig]
             if CustomConfig in PROCESSOR_MAPPING._extra_content:
                del PROCESSOR_MAPPING._extra_content[CustomConfig]
       def    snake_case_			(     self			)	->						List[Any]:
          UpperCamelCase       :    int		      =      AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert'			)
          self.assertEqual(processor.__class__.__name__,     'BertTokenizerFast'			)






       def    snake_case_			(     self			)	->						str:
          UpperCamelCase       :    int		      =      AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext'			)
          self.assertEqual(processor.__class__.__name__,     'ConvNextImageProcessor'			)






@is_staging_test
class 							lowerCAmelCase_						(    unittest.TestCase				):
       UpperCAmelCase__							:   Any  	=    ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
       @classmethod
       def    snake_case_			(     cls			)	->						Dict:
          UpperCamelCase       :    Optional[int]		      =      TOKEN
          HfFolder.save_token(__lowerCamelCase			)
       @classmethod
       def    snake_case_			(     cls			)	->						List[Any]:




          try:
             delete_repo(token=cls._token,     repo_id='test-processor'			)
          except HTTPError:
             pass

          try:
             delete_repo(token=cls._token,     repo_id='valid_org/test-processor-org'			)
          except HTTPError:
             pass

          try:
             delete_repo(token=cls._token,     repo_id='test-dynamic-processor'			)
          except HTTPError:
             pass
       def    snake_case_			(     self			)	->						Dict:
          UpperCamelCase       :    Tuple		      =      WavaVecaProcessor.from_pretrained(__lowerCamelCase			)
          with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(__lowerCamelCase,     'test-processor'			),     push_to_hub=__lowerCamelCase,     use_auth_token=self._token			)

             UpperCamelCase       :    Tuple		      =      WavaVecaProcessor.from_pretrained(F"""{USER}/test-processor"""			)
             for k, v in processor.feature_extractor.__dict__.items():
                self.assertEqual(__lowerCamelCase,     getattr(new_processor.feature_extractor,     __lowerCamelCase			)			)
             self.assertDictEqual(new_processor.tokenizer.get_vocab(),     processor.tokenizer.get_vocab()			)
       def    snake_case_			(     self			)	->						List[str]:
          UpperCamelCase       :    Optional[int]		      =      WavaVecaProcessor.from_pretrained(__lowerCamelCase			)

          with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(__lowerCamelCase,     'test-processor-org'			),     push_to_hub=__lowerCamelCase,     use_auth_token=self._token,     organization='valid_org',     )

             UpperCamelCase       :    int		      =      WavaVecaProcessor.from_pretrained('valid_org/test-processor-org'			)
             for k, v in processor.feature_extractor.__dict__.items():
                self.assertEqual(__lowerCamelCase,     getattr(new_processor.feature_extractor,     __lowerCamelCase			)			)
             self.assertDictEqual(new_processor.tokenizer.get_vocab(),     processor.tokenizer.get_vocab()			)






       def    snake_case_			(     self			)	->						Any:
          CustomFeatureExtractor.register_for_auto_class()
          CustomTokenizer.register_for_auto_class()
          CustomProcessor.register_for_auto_class()

          UpperCamelCase       :    Any		      =      CustomFeatureExtractor.from_pretrained(__lowerCamelCase			)

          with tempfile.TemporaryDirectory() as tmp_dir:
             UpperCamelCase       :    List[Any]		      =      os.path.join(__lowerCamelCase,     'vocab.txt'			)
             with open(__lowerCamelCase,     'w',     encoding='utf-8'			) as vocab_writer:
                vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]			)			)
             UpperCamelCase       :    Optional[int]		      =      CustomTokenizer(__lowerCamelCase			)

          UpperCamelCase       :    Any		      =      CustomProcessor(__lowerCamelCase,     __lowerCamelCase			)

          with tempfile.TemporaryDirectory() as tmp_dir:
             create_repo(F"""{USER}/test-dynamic-processor""",     token=self._token			)
             UpperCamelCase       :    Tuple		      =      Repository(__lowerCamelCase,     clone_from=F"""{USER}/test-dynamic-processor""",     token=self._token			)
             processor.save_pretrained(__lowerCamelCase			)

             # This has added the proper auto_map field to the feature extractor config
             self.assertDictEqual(
                 processor.feature_extractor.auto_map,     {
                     'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor',
                     'AutoProcessor': 'custom_processing.CustomProcessor',
                 },     )

             # This has added the proper auto_map field to the tokenizer config
             with open(os.path.join(__lowerCamelCase,     'tokenizer_config.json'			)			) as f:
                UpperCamelCase       :    Tuple		      =      json.load(__lowerCamelCase			)
             self.assertDictEqual(
                 tokenizer_config['auto_map'],     {
                     'AutoTokenizer': ['custom_tokenization.CustomTokenizer', None],
                     'AutoProcessor': 'custom_processing.CustomProcessor',
                 },     )

             # The code has been copied from fixtures
             self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase,     'custom_feature_extraction.py'			)			)			)
             self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase,     'custom_tokenization.py'			)			)			)
             self.assertTrue(os.path.isfile(os.path.join(__lowerCamelCase,     'custom_processing.py'			)			)			)

             repo.push_to_hub()

          UpperCamelCase       :    Any		      =      AutoProcessor.from_pretrained(F"""{USER}/test-dynamic-processor""",     trust_remote_code=__lowerCamelCase			)
          # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
          self.assertEqual(new_processor.__class__.__name__,     'CustomProcessor'			)










"""simple docstring"""



import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     torch.manual_seed(0    )
     __A       :		List[Any]							=	UNetaDModel(
         sample_size=(32, 64)   ,		in_channels=1   ,		out_channels=1   ,		layers_per_block=2   ,		block_out_channels=(128, 128)   ,		down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''')   ,		up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''')   ,		)
     return model

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     torch.manual_seed(0    )
     __A       :		str							=	UNetaDConditionModel(
         sample_size=(64, 32)   ,		in_channels=1   ,		out_channels=1   ,		layers_per_block=2   ,		block_out_channels=(128, 128)   ,		down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''')   ,		up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''')   ,		cross_attention_dim=10   ,		)
     return model

 @property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     torch.manual_seed(0    )
     __A       :		int							=	AutoencoderKL(
         sample_size=(128, 64)   ,		in_channels=1   ,		out_channels=1   ,		latent_channels=1   ,		layers_per_block=2   ,		block_out_channels=(128, 128)   ,		down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''')   ,		up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''')   ,		)
     __A       :		int							=	UNetaDModel(
         sample_size=(64, 32)   ,		in_channels=1   ,		out_channels=1   ,		layers_per_block=2   ,		block_out_channels=(128, 128)   ,		down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''')   ,		up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''')   ,		)
     return vqvae, unet







 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		str							=	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     __A       :		Union[str, Any]							=	Mel(
         x_res=self.dummy_unet.config.sample_size[1]   ,		y_res=self.dummy_unet.config.sample_size[0]   ,		)

     __A       :		List[Any]							=	DDPMScheduler()
     __A       :		Optional[Any]							=	AudioDiffusionPipeline(vqvae=__lowerCamelCase   ,		unet=self.dummy_unet   ,		mel=__lowerCamelCase   ,		scheduler=__lowerCamelCase    )
     __A       :		Tuple							=	pipe.to(__lowerCamelCase    )
     pipe.set_progress_bar_config(disable=__lowerCamelCase    )

     __A       :		Tuple							=	torch.Generator(device=__lowerCamelCase    ).manual_seed(42    )
     __A       :		List[str]							=	pipe(generator=__lowerCamelCase   ,		steps=4    )
     __A       :		Union[str, Any]							=	output.audios[0]
     __A       :		str							=	output.images[0]

     __A       :		List[Any]							=	torch.Generator(device=__lowerCamelCase    ).manual_seed(42    )
     __A       :		Any							=	pipe(generator=__lowerCamelCase   ,		steps=4   ,		return_dict=__lowerCamelCase    )
     __A       :		int							=	output[0][0]

     assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
     assert (
         image.height == self.dummy_unet.config.sample_size[0]
         and image.width == self.dummy_unet.config.sample_size[1]
     )
     __A       :		Tuple							=	np.frombuffer(image.tobytes()   ,		dtype='''uint8'''    )[:10]
     __A       :		str							=	np.frombuffer(image_from_tuple.tobytes()   ,		dtype='''uint8'''    )[:10]
     __A       :		Any							=	np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]    )

     assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() == 0

     __A       :		int							=	Mel(
         x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]   ,		y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]   ,		)

     __A       :		Any							=	DDIMScheduler()
     __A       :		Optional[Any]							=	self.dummy_vqvae_and_unet
     __A       :		int							=	AudioDiffusionPipeline(
         vqvae=self.dummy_vqvae_and_unet[0]   ,		unet=dummy_vqvae_and_unet[1]   ,		mel=__lowerCamelCase   ,		scheduler=__lowerCamelCase    )
     __A       :		Any							=	pipe.to(__lowerCamelCase    )
     pipe.set_progress_bar_config(disable=__lowerCamelCase    )

     np.random.seed(0    )
     __A       :		str							=	np.random.uniform(-1   ,		1   ,		((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)    )
     __A       :		Union[str, Any]							=	torch.Generator(device=__lowerCamelCase    ).manual_seed(42    )
     __A       :		int							=	pipe(raw_audio=__lowerCamelCase   ,		generator=__lowerCamelCase   ,		start_step=5   ,		steps=10    )
     __A       :		Any							=	output.images[0]

     assert (
         image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
         and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
     )
     __A       :		str							=	np.frombuffer(image.tobytes()   ,		dtype='''uint8'''    )[:10]
     __A       :		Optional[Any]							=	np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]    )

     assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0

     __A       :		Union[str, Any]							=	self.dummy_unet_condition
     __A       :		List[str]							=	AudioDiffusionPipeline(
         vqvae=self.dummy_vqvae_and_unet[0]   ,		unet=__lowerCamelCase   ,		mel=__lowerCamelCase   ,		scheduler=__lowerCamelCase    )
     __A       :		Dict							=	pipe.to(__lowerCamelCase    )
     pipe.set_progress_bar_config(disable=__lowerCamelCase    )

     np.random.seed(0    )
     __A       :		int							=	torch.rand((1, 1, 10)    )
     __A       :		Optional[Any]							=	pipe(generator=__lowerCamelCase   ,		encoding=__lowerCamelCase    )
     __A       :		str							=	output.images[0]
     __A       :		Optional[Any]							=	np.frombuffer(image.tobytes()   ,		dtype='''uint8'''    )[:10]
     __A       :		Tuple							=	np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]    )

     assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0






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





 """simple docstring"""


 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		int							=	torch_device

     __A       :		List[Any]							=	DiffusionPipeline.from_pretrained('''teticio/audio-diffusion-ddim-256'''    )
     __A       :		List[Any]							=	pipe.to(__lowerCamelCase    )
     pipe.set_progress_bar_config(disable=__lowerCamelCase    )

     __A       :		Dict							=	torch.Generator(device=__lowerCamelCase    ).manual_seed(42    )
     __A       :		str							=	pipe(generator=__lowerCamelCase    )
     __A       :		Dict							=	output.audios[0]
     __A       :		List[Any]							=	output.images[0]

     assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
     assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
     __A       :		Optional[int]							=	np.frombuffer(image.tobytes()   ,		dtype='''uint8'''    )[:10]
     __A       :		Optional[Any]							=	np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]    )

     assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0




