
'''simple docstring'''







import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference






class  lowerCAmelCase__   (  lowerCamelCase_    ,						unittest.TestCase     ):
					lowerCAmelCase_        =     ShapEImgaImgPipeline
					lowerCAmelCase_        =     ['''image''']
					lowerCAmelCase_        =     ['''image''']
					lowerCAmelCase_        =     [
					    '''num_images_per_prompt''',
					    '''num_inference_steps''',
					    '''generator''',
					    '''latents''',
					    '''guidance_scale''',
					    '''frame_size''',
					    '''output_type''',
					    '''return_dict''',
					]
					lowerCAmelCase_        =     False






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											return 32






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											return 32






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											return self.time_input_dim * 4






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											return 8






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											torch.manual_seed(0		)
											lowercase_	:     Any													=       CLIPVisionConfig(
											    hidden_size=self.text_embedder_hidden_size				,							image_size=64				,							projection_dim=self.text_embedder_hidden_size				,							intermediate_size=37				,							num_attention_heads=4				,							num_channels=3				,							num_hidden_layers=5				,							patch_size=1				,							)

											lowercase_	:     Tuple													=       CLIPVisionModel(__SCREAMING_SNAKE_CASE		)
											return model






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Union[str, Any]													=       CLIPImageProcessor(
											    crop_size=2_24				,							do_center_crop=__SCREAMING_SNAKE_CASE				,							do_normalize=__SCREAMING_SNAKE_CASE				,							do_resize=__SCREAMING_SNAKE_CASE				,							image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]				,							image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]				,							resample=3				,							size=2_24				,							)

											return image_processor






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											torch.manual_seed(0		)

											lowercase_	:     List[Any]													=       {
											    '''num_attention_heads''': 2,
											    '''attention_head_dim''': 16,
											    '''embedding_dim''': self.time_input_dim,
											    '''num_embeddings''': 32,
											    '''embedding_proj_dim''': self.text_embedder_hidden_size,
											    '''time_embed_dim''': self.time_embed_dim,
											    '''num_layers''': 1,
											    '''clip_embed_dim''': self.time_input_dim * 2,
											    '''additional_embeddings''': 0,
											    '''time_embed_act_fn''': '''gelu''',
											    '''norm_in_type''': '''layer''',
											    '''embedding_proj_norm_type''': '''layer''',
											    '''encoder_hid_proj_type''': None,
											    '''added_emb_type''': None,
											}

											lowercase_	:     Any													=       PriorTransformer(**__SCREAMING_SNAKE_CASE		)
											return model






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											torch.manual_seed(0		)

											lowercase_	:     Union[str, Any]													=       {
											    '''param_shapes''': (
											        (self.renderer_dim, 93),
											        (self.renderer_dim, 8),
											        (self.renderer_dim, 8),
											        (self.renderer_dim, 8),
											    ),
											    '''d_latent''': self.time_input_dim,
											    '''d_hidden''': self.renderer_dim,
											    '''n_output''': 12,
											    '''background''': (
											        0.1,
											        0.1,
											        0.1,
											    ),
											}
											lowercase_	:     Optional[Any]													=       ShapERenderer(**__SCREAMING_SNAKE_CASE		)
											return model






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     str													=       self.dummy_prior
											lowercase_	:     Union[str, Any]													=       self.dummy_image_encoder
											lowercase_	:     Tuple													=       self.dummy_image_processor
											lowercase_	:     Optional[Any]													=       self.dummy_renderer

											lowercase_	:     Tuple													=       HeunDiscreteScheduler(
											    beta_schedule='''exp'''				,							num_train_timesteps=10_24				,							prediction_type='''sample'''				,							use_karras_sigmas=__SCREAMING_SNAKE_CASE				,							clip_sample=__SCREAMING_SNAKE_CASE				,							clip_sample_range=1.0				,							)
											lowercase_	:     Dict													=       {
											    '''prior''': prior,
											    '''image_encoder''': image_encoder,
											    '''image_processor''': image_processor,
											    '''renderer''': renderer,
											    '''scheduler''': scheduler,
											}

											return components






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE=0		):


											"""simple docstring"""





											lowercase_	:     List[Any]													=       floats_tensor((1, 3, 64, 64)				,							rng=random.Random(__SCREAMING_SNAKE_CASE		)		).to(__SCREAMING_SNAKE_CASE		)

											if str(__SCREAMING_SNAKE_CASE		).startswith('''mps'''		):
																	lowercase_	:     int													=       torch.manual_seed(__SCREAMING_SNAKE_CASE		)
											else:
																	lowercase_	:     List[Any]													=       torch.Generator(device=__SCREAMING_SNAKE_CASE		).manual_seed(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[Any]													=       {
											    '''image''': input_image,
											    '''generator''': generator,
											    '''num_inference_steps''': 1,
											    '''frame_size''': 32,
											    '''output_type''': '''np''',
											}
											return inputs






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     List[str]													=       '''cpu'''

											lowercase_	:     List[str]													=       self.get_dummy_components()

											lowercase_	:     Optional[int]													=       self.pipeline_class(**__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       pipe.to(__SCREAMING_SNAKE_CASE		)

											pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     List[str]													=       pipe(**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE		)		)
											lowercase_	:     List[Any]													=       output.images[0]
											lowercase_	:     Union[str, Any]													=       image[0, -3:, -3:, -1]

											assert image.shape == (20, 32, 32, 3)

											lowercase_	:     Optional[Any]													=       np.array(
											    [
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											    ]		)

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






					def 	_snake_case    (   self		):


											"""simple docstring"""





											self._test_inference_batch_consistent(batch_sizes=[1, 2]		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     List[str]													=       torch_device == '''cpu'''
											lowercase_	:     int													=       True
											self._test_inference_batch_single_identical(
											    batch_size=2				,							test_max_difference=__SCREAMING_SNAKE_CASE				,							relax_max_difference=__SCREAMING_SNAKE_CASE				,							)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     List[str]													=       self.get_dummy_components()
											lowercase_	:     Optional[Any]													=       self.pipeline_class(**__SCREAMING_SNAKE_CASE		)
											lowercase_	:     str													=       pipe.to(__SCREAMING_SNAKE_CASE		)
											pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     List[str]													=       1
											lowercase_	:     Any													=       2

											lowercase_	:     str													=       self.get_dummy_inputs(__SCREAMING_SNAKE_CASE		)

											for key in inputs.keys():
																	if key in self.batch_params:
																							lowercase_	:     Optional[int]													=       batch_size * [inputs[key]]

											lowercase_	:     Any													=       pipe(**__SCREAMING_SNAKE_CASE				,							num_images_per_prompt=__SCREAMING_SNAKE_CASE		)[0]

											assert images.shape[0] == batch_size * num_images_per_prompt







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






					def 	_snake_case    (   self		):


											"""simple docstring"""





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






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Dict													=       load_image(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png'''		)
											lowercase_	:     Tuple													=       load_numpy(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											    '''/shap_e/test_shap_e_img2img_out.npy'''		)
											lowercase_	:     Optional[Any]													=       ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img'''		)
											lowercase_	:     List[str]													=       pipe.to(__SCREAMING_SNAKE_CASE		)
											pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Optional[Any]													=       torch.Generator(device=__SCREAMING_SNAKE_CASE		).manual_seed(0		)

											lowercase_	:     Union[str, Any]													=       pipe(
											    __SCREAMING_SNAKE_CASE				,							generator=__SCREAMING_SNAKE_CASE				,							guidance_scale=3.0				,							num_inference_steps=64				,							frame_size=64				,							output_type='''np'''				,							).images[0]

											assert images.shape == (20, 64, 64, 3)

											assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)










import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A									=				logging.get_logger(__name__)

__A									=				{
    "microsoft/unispeech-large-1500h-cv": (
        "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json"
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			"unispeech"

 def __init__(self				:   Any       , UpperCAmelCase_				:   Any=32       , UpperCAmelCase_				:   List[str]=768       , UpperCAmelCase_				:   Any=12       , UpperCAmelCase_				:   Union[str, Any]=12       , UpperCAmelCase_				:   Optional[Any]=3_072       , UpperCAmelCase_				:   List[Any]="gelu"       , UpperCAmelCase_				:   int=0.1       , UpperCAmelCase_				:   Optional[int]=0.1       , UpperCAmelCase_				:   int=0.1       , UpperCAmelCase_				:   Any=0.0       , UpperCAmelCase_				:   str=0.0       , UpperCAmelCase_				:   Dict=0.1       , UpperCAmelCase_				:   Optional[int]=0.1       , UpperCAmelCase_				:   Optional[Any]=0.02       , UpperCAmelCase_				:   Union[str, Any]=1E-5       , UpperCAmelCase_				:   str="group"       , UpperCAmelCase_				:   List[Any]="gelu"       , UpperCAmelCase_				:   Tuple=(512, 512, 512, 512, 512, 512, 512)       , UpperCAmelCase_				:   str=(5, 2, 2, 2, 2, 2, 2)       , UpperCAmelCase_				:   Any=(10, 3, 3, 3, 3, 2, 2)       , UpperCAmelCase_				:   Optional[Any]=False       , UpperCAmelCase_				:   str=128       , UpperCAmelCase_				:   int=16       , UpperCAmelCase_				:   Dict=False       , UpperCAmelCase_				:   Optional[int]=True       , UpperCAmelCase_				:   Dict=0.05       , UpperCAmelCase_				:   Optional[int]=10       , UpperCAmelCase_				:   Tuple=2       , UpperCAmelCase_				:   Union[str, Any]=0.0       , UpperCAmelCase_				:   int=10       , UpperCAmelCase_				:   List[Any]=0       , UpperCAmelCase_				:   Optional[Any]=320       , UpperCAmelCase_				:   int=2       , UpperCAmelCase_				:   Union[str, Any]=0.1       , UpperCAmelCase_				:   str=100       , UpperCAmelCase_				:   Any=256       , UpperCAmelCase_				:   int=256       , UpperCAmelCase_				:   Optional[Any]=0.1       , UpperCAmelCase_				:   str="mean"       , UpperCAmelCase_				:   Union[str, Any]=False       , UpperCAmelCase_				:   List[str]=False       , UpperCAmelCase_				:   List[Any]=256       , UpperCAmelCase_				:   Optional[int]=80       , UpperCAmelCase_				:   Optional[int]=0       , UpperCAmelCase_				:   Optional[Any]=1       , UpperCAmelCase_				:   Union[str, Any]=2       , UpperCAmelCase_				:   Dict=0.5       , **UpperCAmelCase_				:   Optional[int]       , )       ->str:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_       , pad_token_id=UpperCAmelCase_       , bos_token_id=UpperCAmelCase_       , eos_token_id=UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =hidden_size
   lowerCamelCase__:      List[str]			  =feat_extract_norm
   lowerCamelCase__:      Dict			  =feat_extract_activation
   lowerCamelCase__:      Optional[Any]			  =list(UpperCAmelCase_)
   lowerCamelCase__:      Any			  =list(UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =list(UpperCAmelCase_)
   lowerCamelCase__:      Dict			  =conv_bias
   lowerCamelCase__:      Optional[Any]			  =num_conv_pos_embeddings
   lowerCamelCase__:      Dict			  =num_conv_pos_embedding_groups
   lowerCamelCase__:      int			  =len(self.conv_dim)
   lowerCamelCase__:      Union[str, Any]			  =num_hidden_layers
   lowerCamelCase__:      Union[str, Any]			  =intermediate_size
   lowerCamelCase__:      Dict			  =hidden_act
   lowerCamelCase__:      List[Any]			  =num_attention_heads
   lowerCamelCase__:      Dict			  =hidden_dropout
   lowerCamelCase__:      Optional[Any]			  =attention_dropout
   lowerCamelCase__:      Optional[Any]			  =activation_dropout
   lowerCamelCase__:      Tuple			  =feat_proj_dropout
   lowerCamelCase__:      int			  =final_dropout
   lowerCamelCase__:      Optional[Any]			  =layerdrop
   lowerCamelCase__:      Dict			  =layer_norm_eps
   lowerCamelCase__:      Optional[Any]			  =initializer_range
   lowerCamelCase__:      int			  =num_ctc_classes
   lowerCamelCase__:      Tuple			  =vocab_size
   lowerCamelCase__:      Dict			  =do_stable_layer_norm
   lowerCamelCase__:      List[Any]			  =use_weighted_layer_sum
   lowerCamelCase__:      Dict			  =classifier_proj_size

   if (
       (len(self.conv_stride) != self.num_feat_extract_layers)
       or (len(self.conv_kernel) != self.num_feat_extract_layers)
       or (len(self.conv_dim) != self.num_feat_extract_layers)
   ):
     raise ValueError(
         "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
         " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
         F""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"""
         F""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""")

   # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
   lowerCamelCase__:      int			  =apply_spec_augment
   lowerCamelCase__:      List[str]			  =mask_time_prob
   lowerCamelCase__:      Union[str, Any]			  =mask_time_length
   lowerCamelCase__:      List[Any]			  =mask_time_min_masks
   lowerCamelCase__:      Any			  =mask_feature_prob
   lowerCamelCase__:      Optional[Any]			  =mask_feature_length
   lowerCamelCase__:      List[str]			  =mask_feature_min_masks

   # parameters for pretraining with codevector quantized representations
   lowerCamelCase__:      Optional[Any]			  =num_codevectors_per_group
   lowerCamelCase__:      str			  =num_codevector_groups
   lowerCamelCase__:      Tuple			  =contrastive_logits_temperature
   lowerCamelCase__:      int			  =feat_quantizer_dropout
   lowerCamelCase__:      Any			  =num_negatives
   lowerCamelCase__:      List[str]			  =codevector_dim
   lowerCamelCase__:      Union[str, Any]			  =proj_codevector_dim
   lowerCamelCase__:      Any			  =diversity_loss_weight

   # ctc loss
   lowerCamelCase__:      Any			  =ctc_loss_reduction
   lowerCamelCase__:      Dict			  =ctc_zero_infinity

   # pretraining loss
   lowerCamelCase__:      Dict			  =replace_prob







 @property
 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Optional[Any]:



   '''simple docstring'''



   return functools.reduce(operator.mul       , self.conv_stride       , 1)

