



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class        UpperCAmelCase_  (       UpperCamelCase_   ,   unittest.TestCase	):

						'''simple docstring'''




						UpperCamelCase__      :			Tuple      =  LDMTextToImagePipeline
						UpperCamelCase__      :			Optional[Any]      =  TEXT_TO_IMAGE_PARAMS - {
						    '''negative_prompt''',
						    '''negative_prompt_embeds''',
						    '''cross_attention_kwargs''',
						    '''prompt_embeds''',
						}
						UpperCamelCase__      :			Dict      =  PipelineTesterMixin.required_optional_params - {
						    '''num_images_per_prompt''',
						    '''callback''',
						    '''callback_steps''',
						}
						UpperCamelCase__      :			Union[str, Any]      =  TEXT_TO_IMAGE_BATCH_PARAMS
						UpperCamelCase__      :			Any      =  False






						def 	_A     (   self		):







													'''simple docstring'''

													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= UNetaDConditionModel(
													    block_out_channels=(32, 64)				,							layers_per_block=2				,							sample_size=32				,							in_channels=4				,							out_channels=4				,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,							up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')				,							cross_attention_dim=32				,							)
													__SCREAMING_SNAKE_CASE									= DDIMScheduler(
													    beta_start=0.0_0_0_8_5				,							beta_end=0.0_1_2				,							beta_schedule='scaled_linear'				,							clip_sample=_A				,							set_alpha_to_one=_A				,							)
													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= AutoencoderKL(
													    block_out_channels=(32, 64)				,							in_channels=3				,							out_channels=3				,							down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')				,							up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')				,							latent_channels=4				,							)
													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= CLIPTextConfig(
													    bos_token_id=0				,							eos_token_id=2				,							hidden_size=32				,							intermediate_size=37				,							layer_norm_eps=1e-05				,							num_attention_heads=4				,							num_hidden_layers=5				,							pad_token_id=1				,							vocab_size=1_000				,							)
													__SCREAMING_SNAKE_CASE									= CLIPTextModel(_A		)
													__SCREAMING_SNAKE_CASE									= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

													__SCREAMING_SNAKE_CASE									= {
													    'unet': unet,
													    'scheduler': scheduler,
													    'vqvae': vae,
													    'bert': text_encoder,
													    'tokenizer': tokenizer,
													}
													return components






						def 	_A     (   self				,							_A				,							_A=0		):







													'''simple docstring'''

													if str(_A		).startswith('mps'		):
																				__SCREAMING_SNAKE_CASE									= torch.manual_seed(_A		)
													else:
																				__SCREAMING_SNAKE_CASE									= torch.Generator(device=_A		).manual_seed(_A		)
													__SCREAMING_SNAKE_CASE									= {
													    'prompt': 'A painting of a squirrel eating a burger',
													    'generator': generator,
													    'num_inference_steps': 2,
													    'guidance_scale': 6.0,
													    'output_type': 'numpy',
													}
													return inputs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 'cpu'  # ensure determinism for the device-dependent torch.Generator

													__SCREAMING_SNAKE_CASE									= self.get_dummy_components()
													__SCREAMING_SNAKE_CASE									= LDMTextToImagePipeline(**_A		)
													pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_dummy_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		).images
													__SCREAMING_SNAKE_CASE									= image[0, -3:, -3:, -1]

													assert image.shape == (1, 16, 16, 3)
													__SCREAMING_SNAKE_CASE									= np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]		)

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







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

						'''simple docstring'''




						def 	_A     (   self		):







													'''simple docstring'''

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






						def 	_A     (   self				,							_A				,							_A=torch.floataa				,							_A=0		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= torch.manual_seed(_A		)
													__SCREAMING_SNAKE_CASE									= np.random.RandomState(_A		).standard_normal((1, 4, 32, 32)		)
													__SCREAMING_SNAKE_CASE									= torch.from_numpy(_A		).to(device=_A				,							dtype=_A		)
													__SCREAMING_SNAKE_CASE									= {
													    'prompt': 'A painting of a squirrel eating a burger',
													    'latents': latents,
													    'generator': generator,
													    'num_inference_steps': 3,
													    'guidance_scale': 6.0,
													    'output_type': 'numpy',
													}
													return inputs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'		).to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		).images
													__SCREAMING_SNAKE_CASE									= image[0, -3:, -3:, -1].flatten()

													assert image.shape == (1, 256, 256, 3)
													__SCREAMING_SNAKE_CASE									= np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]		)
													__SCREAMING_SNAKE_CASE									= np.abs(expected_slice - image_slice		).max()
													assert max_diff < 1e-3







@nightly
@require_torch_gpu
class        UpperCAmelCase_  (       unittest.TestCase	):

						'''simple docstring'''




						def 	_A     (   self		):







													'''simple docstring'''

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






						def 	_A     (   self				,							_A				,							_A=torch.floataa				,							_A=0		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= torch.manual_seed(_A		)
													__SCREAMING_SNAKE_CASE									= np.random.RandomState(_A		).standard_normal((1, 4, 32, 32)		)
													__SCREAMING_SNAKE_CASE									= torch.from_numpy(_A		).to(device=_A				,							dtype=_A		)
													__SCREAMING_SNAKE_CASE									= {
													    'prompt': 'A painting of a squirrel eating a burger',
													    'latents': latents,
													    'generator': generator,
													    'num_inference_steps': 50,
													    'guidance_scale': 6.0,
													    'output_type': 'numpy',
													}
													return inputs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'		).to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		).images[0]

													__SCREAMING_SNAKE_CASE									= load_numpy(
													    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'		)
													__SCREAMING_SNAKE_CASE									= np.abs(expected_image - image		).max()
													assert max_diff < 1e-3











import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Union[str, Any]      =  '''Wav2Vec2FeatureExtractor'''
						UpperCamelCase__      :			Union[str, Any]      =  '''AutoTokenizer'''






						def __init__(   self				,							_A				,							_A		):







													'''simple docstring'''

													super().__init__(_A				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.feature_extractor
													__SCREAMING_SNAKE_CASE									= False






						@classmethod
						def 	_A     (   cls				,							_A				,							**_A		):







													'''simple docstring'''

													try:
																				return super().from_pretrained(_A				,							**_A		)
													except OSError:
																				warnings.warn(
																				    f"""Loading a tokenizer inside {cls.__name__} from a config that does not"""
																				    ' include a `tokenizer_class` attribute is deprecated and will be '
																				    'removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`'
																				    ' attribute to either your `config.json` or `tokenizer_config.json` '
																				    'file to suppress this warning: '				,							_A				,							)

																				__SCREAMING_SNAKE_CASE									= WavaVecaFeatureExtractor.from_pretrained(_A				,							**_A		)
																				__SCREAMING_SNAKE_CASE									= WavaVecaCTCTokenizer.from_pretrained(_A				,							**_A		)

																				return cls(feature_extractor=_A				,							tokenizer=_A		)






						def __call__(   self				,							*_A				,							**_A		):







													'''simple docstring'''

													if self._in_target_context_manager:
																				return self.current_processor(*_A				,							**_A		)

													if "raw_speech" in kwargs:
																				warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'		)
																				__SCREAMING_SNAKE_CASE									= kwargs.pop('raw_speech'		)
													else:
																				__SCREAMING_SNAKE_CASE									= kwargs.pop('audio'				,							_A		)
													__SCREAMING_SNAKE_CASE									= kwargs.pop('sampling_rate'				,							_A		)
													__SCREAMING_SNAKE_CASE									= kwargs.pop('text'				,							_A		)
													if len(_A		) > 0:
																				__SCREAMING_SNAKE_CASE									= args[0]
																				__SCREAMING_SNAKE_CASE									= args[1:]

													if audio is None and text is None:
																				raise ValueError('You need to specify either an `audio` or `text` input to process.'		)

													if audio is not None:
																				__SCREAMING_SNAKE_CASE									= self.feature_extractor(_A				,							*_A				,							sampling_rate=_A				,							**_A		)
													if text is not None:
																				__SCREAMING_SNAKE_CASE									= self.tokenizer(_A				,							**_A		)

													if text is None:
																				return inputs
													elif audio is None:
																				return encodings
													else:
																				__SCREAMING_SNAKE_CASE									= encodings['input_ids']
																				return inputs






						def 	_A     (   self				,							*_A				,							**_A		):







													'''simple docstring'''

													if self._in_target_context_manager:
																				return self.current_processor.pad(*_A				,							**_A		)

													__SCREAMING_SNAKE_CASE									= kwargs.pop('input_features'				,							_A		)
													__SCREAMING_SNAKE_CASE									= kwargs.pop('labels'				,							_A		)
													if len(_A		) > 0:
																				__SCREAMING_SNAKE_CASE									= args[0]
																				__SCREAMING_SNAKE_CASE									= args[1:]

													if input_features is not None:
																				__SCREAMING_SNAKE_CASE									= self.feature_extractor.pad(_A				,							*_A				,							**_A		)
													if labels is not None:
																				__SCREAMING_SNAKE_CASE									= self.tokenizer.pad(_A				,							**_A		)

													if labels is None:
																				return input_features
													elif input_features is None:
																				return labels
													else:
																				__SCREAMING_SNAKE_CASE									= labels['input_ids']
																				return input_features






						def 	_A     (   self				,							*_A				,							**_A		):







													'''simple docstring'''

													return self.tokenizer.batch_decode(*_A				,							**_A		)






						def 	_A     (   self				,							*_A				,							**_A		):







													'''simple docstring'''

													return self.tokenizer.decode(*_A				,							**_A		)






						@contextmanager
						def 	_A     (   self		):







													'''simple docstring'''

													warnings.warn(
													    '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '
													    'labels by using the argument `text` of the regular `__call__` method (either in the same call as '
													    'your audio inputs, or in a separate call.'		)
													__SCREAMING_SNAKE_CASE									= True
													__SCREAMING_SNAKE_CASE									= self.tokenizer
													yield
													__SCREAMING_SNAKE_CASE									= self.feature_extractor
													__SCREAMING_SNAKE_CASE									= False






