






'''simple docstring'''

from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule







def     lowercase__ (      __UpperCamelCase		,						__UpperCamelCase		,						__UpperCamelCase=1E-12    )-> Any:
      UpperCamelCase				  =					jnp.divide(emb_a.T		,						jnp.clip(jnp.linalg.norm(snake_case_		,						axis=1    )		,						a_min=snake_case_    )    ).T
      UpperCamelCase				  =					jnp.divide(emb_a.T		,						jnp.clip(jnp.linalg.norm(snake_case_		,						axis=1    )		,						a_min=snake_case_    )    ).T
      return jnp.matmul(snake_case_		,						norm_emb_a.T    )






class 				a_						(			nn.Module				):
  lowercase     		=      42
  lowercase     		=      jnp.floataa

  def   A__						(      self      )  ->      List[str]:



        """simple docstring"""






        UpperCamelCase				  =					FlaxCLIPVisionModule(self.config.vision_config      )
        UpperCamelCase				  =					nn.Dense(self.config.projection_dim			,		use_bias=__lowerCamelCase			,		dtype=self.dtype      )

        UpperCamelCase				  =					self.param("""concept_embeds"""			,		jax.nn.initializers.ones			,		(17, self.config.projection_dim)      )
        UpperCamelCase				  =					self.param(
            """special_care_embeds"""			,		jax.nn.initializers.ones			,		(3, self.config.projection_dim)      )

        UpperCamelCase				  =					self.param("""concept_embeds_weights"""			,		jax.nn.initializers.ones			,		(17,)      )
        UpperCamelCase				  =					self.param("""special_care_embeds_weights"""			,		jax.nn.initializers.ones			,		(3,)      )


  def __call__(      self			,		_SCREAMING_SNAKE_CASE      )  ->      Optional[Any]:



        """simple docstring"""






        UpperCamelCase				  =					self.vision_model(__lowerCamelCase      )[1]
        UpperCamelCase				  =					self.visual_projection(__lowerCamelCase      )

        UpperCamelCase				  =					jax_cosine_distance(__lowerCamelCase			,		self.special_care_embeds      )
        UpperCamelCase				  =					jax_cosine_distance(__lowerCamelCase			,		self.concept_embeds      )

        # increase this value to create a stronger `nfsw` filter
        # at the cost of increasing the possibility of filtering benign image inputs
        UpperCamelCase				  =					0.0

        UpperCamelCase				  =					special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
        UpperCamelCase				  =					jnp.round(__lowerCamelCase			,		3      )
        UpperCamelCase				  =					jnp.any(special_scores > 0			,		axis=1			,		keepdims=__lowerCamelCase      )
        # Use a lower threshold if an image has any special care concept
        UpperCamelCase				  =					is_special_care * 0.0_1

        UpperCamelCase				  =					cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
        UpperCamelCase				  =					jnp.round(__lowerCamelCase			,		3      )
        UpperCamelCase				  =					jnp.any(concept_scores > 0			,		axis=1      )

        return has_nsfw_concepts






class 				a_						(			SCREAMING_SNAKE_CASE__				):
  lowercase     		=      CLIPConfig
  lowercase     		=      """clip_input"""
  lowercase     		=      FlaxStableDiffusionSafetyCheckerModule

  def __init__(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE = None			,		_SCREAMING_SNAKE_CASE = 0			,		_SCREAMING_SNAKE_CASE = jnp.floataa			,		_SCREAMING_SNAKE_CASE = True			,		**_SCREAMING_SNAKE_CASE			,		)  ->      int:



        """simple docstring"""






        if input_shape is None:
              UpperCamelCase				  =					(1, 224, 224, 3)
        UpperCamelCase				  =					self.module_class(config=__lowerCamelCase			,		dtype=__lowerCamelCase			,		**__lowerCamelCase      )
        super().__init__(__lowerCamelCase			,		__lowerCamelCase			,		input_shape=__lowerCamelCase			,		seed=__lowerCamelCase			,		dtype=__lowerCamelCase			,		_do_init=_do_init      )

  def   A__						(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE = None      )  ->      Optional[int]:



        """simple docstring"""






        UpperCamelCase				  =					jax.random.normal(__lowerCamelCase			,		__lowerCamelCase      )

        UpperCamelCase				  =					jax.random.split(__lowerCamelCase      )
        UpperCamelCase				  =					{'''params''': params_rng, '''dropout''': dropout_rng}

        UpperCamelCase				  =					self.module.init(__lowerCamelCase			,		__lowerCamelCase      )['''params''']

        return random_params


  def __call__(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE = None			,		)  ->      Tuple:



        """simple docstring"""






        UpperCamelCase				  =					jnp.transpose(__lowerCamelCase			,		(0, 2, 3, 1)      )

        return self.module.apply(
            {"""params""": params or self.params}			,		jnp.array(__lowerCamelCase			,		dtype=jnp.floataa      )			,		rngs={}			,		)







"""simple docstring"""



from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     ["""vqvae"""]

 def __init__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						):



     '''simple docstring'''




     super().__init__()
     self.register_modules(unet=__lowerCamelCase					,						scheduler=__lowerCamelCase					,						mel=__lowerCamelCase					,						vqvae=__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     return 50 if isinstance(self.scheduler					,						__lowerCamelCase  ) else 1000

 @torch.no_grad()
 def __call__(    self					,						__lowerCamelCase = 1					,						__lowerCamelCase = None					,						__lowerCamelCase = None					,						__lowerCamelCase = 0					,						__lowerCamelCase = 0					,						__lowerCamelCase = None					,						__lowerCamelCase = None					,						__lowerCamelCase = 0					,						__lowerCamelCase = 0					,						__lowerCamelCase = None					,						__lowerCamelCase = 0					,						__lowerCamelCase = None					,						__lowerCamelCase = None					,						__lowerCamelCase=True					,						):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     steps or self.get_default_steps()
     self.scheduler.set_timesteps(__lowerCamelCase  )
     __A    :						Any						 =     step_generator or generator
     # For backwards compatibility
     if type(self.unet.config.sample_size  ) == int:
         __A    :						Optional[Any]						 =     (self.unet.config.sample_size, self.unet.config.sample_size)
     if noise is None:
         __A    :						Dict						 =     randn_tensor(
             (
                 batch_size,
                 self.unet.config.in_channels,
                 self.unet.config.sample_size[0],
                 self.unet.config.sample_size[1],
             )					,						generator=__lowerCamelCase					,						device=self.device					,						)
     __A    :						Optional[int]						 =     noise
     __A    :						int						 =     None

     if audio_file is not None or raw_audio is not None:
         self.mel.load_audio(__lowerCamelCase					,						__lowerCamelCase  )
         __A    :						int						 =     self.mel.audio_slice_to_image(__lowerCamelCase  )
         __A    :						Optional[Any]						 =     np.frombuffer(input_image.tobytes()					,						dtype='''uint8'''  ).reshape(
             (input_image.height, input_image.width)  )
         __A    :						Union[str, Any]						 =     (input_image / 255) * 2 - 1
         __A    :						Any						 =     torch.tensor(input_image[np.newaxis, :, :]					,						dtype=torch.float  ).to(self.device  )

         if self.vqvae is not None:
             __A    :						Any						 =     self.vqvae.encode(torch.unsqueeze(__lowerCamelCase					,						0  )  ).latent_dist.sample(
                 generator=__lowerCamelCase  )[0]
             __A    :						Optional[Any]						 =     self.vqvae.config.scaling_factor * input_images

         if start_step > 0:
             __A    :						Union[str, Any]						 =     self.scheduler.add_noise(__lowerCamelCase					,						__lowerCamelCase					,						self.scheduler.timesteps[start_step - 1]  )

         __A    :						Optional[int]						 =     (
             self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
         )
         __A    :						int						 =     int(mask_start_secs * pixels_per_second  )
         __A    :						Dict						 =     int(mask_end_secs * pixels_per_second  )
         __A    :						int						 =     self.scheduler.add_noise(__lowerCamelCase					,						__lowerCamelCase					,						torch.tensor(self.scheduler.timesteps[start_step:]  )  )

     for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]  )  ):
         if isinstance(self.unet					,						__lowerCamelCase  ):
             __A    :						List[str]						 =     self.unet(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  )['''sample''']
         else:
             __A    :						List[str]						 =     self.unet(__lowerCamelCase					,						__lowerCamelCase  )['''sample''']

         if isinstance(self.scheduler					,						__lowerCamelCase  ):
             __A    :						Optional[Any]						 =     self.scheduler.step(
                 model_output=__lowerCamelCase					,						timestep=__lowerCamelCase					,						sample=__lowerCamelCase					,						eta=__lowerCamelCase					,						generator=__lowerCamelCase					,						)['''prev_sample''']
         else:
             __A    :						Optional[Any]						 =     self.scheduler.step(
                 model_output=__lowerCamelCase					,						timestep=__lowerCamelCase					,						sample=__lowerCamelCase					,						generator=__lowerCamelCase					,						)['''prev_sample''']

         if mask is not None:
             if mask_start > 0:
                 __A    :						Optional[Any]						 =     mask[:, step, :, :mask_start]
             if mask_end > 0:
                 __A    :						Tuple						 =     mask[:, step, :, -mask_end:]

     if self.vqvae is not None:
         # 0.18215 was scaling factor used in training to ensure unit variance
         __A    :						Union[str, Any]						 =     1 / self.vqvae.config.scaling_factor * images
         __A    :						List[str]						 =     self.vqvae.decode(__lowerCamelCase  )['''sample''']

     __A    :						Any						 =     (images / 2 + 0.5).clamp(0					,						1  )
     __A    :						Any						 =     images.cpu().permute(0					,						2					,						3					,						1  ).numpy()
     __A    :						Any						 =     (images * 255).round().astype('''uint8'''  )
     __A    :						List[Any]						 =     list(
         (Image.fromarray(_[:, :, 0]  ) for _ in images)
         if images.shape[3] == 1
         else (Image.fromarray(__lowerCamelCase					,						mode='''RGB'''  ).convert('''L'''  ) for _ in images)  )

     __A    :						Dict						 =     [self.mel.image_to_audio(__lowerCamelCase  ) for _ in images]
     if not return_dict:
         return images, (self.mel.get_sample_rate(), audios)

     return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase  )[:, np.newaxis, :]  )					,						**ImagePipelineOutput(__lowerCamelCase  )  )

 @torch.no_grad()
 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase = 50  ):



     '''simple docstring'''




     assert isinstance(self.scheduler					,						__lowerCamelCase  )
     self.scheduler.set_timesteps(__lowerCamelCase  )
     __A    :						str						 =     np.array(
         [np.frombuffer(image.tobytes()					,						dtype='''uint8'''  ).reshape((1, image.height, image.width)  ) for image in images]  )
     __A    :						Any						 =     (sample / 255) * 2 - 1
     __A    :						Dict						 =     torch.Tensor(__lowerCamelCase  ).to(self.device  )

     for t in self.progress_bar(torch.flip(self.scheduler.timesteps					,						(0,)  )  ):
         __A    :						Tuple						 =     t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
         __A    :						List[Any]						 =     self.scheduler.alphas_cumprod[t]
         __A    :						Optional[int]						 =     (
             self.scheduler.alphas_cumprod[prev_timestep]
             if prev_timestep >= 0
             else self.scheduler.final_alpha_cumprod
         )
         __A    :						List[Any]						 =     1 - alpha_prod_t
         __A    :						int						 =     self.unet(__lowerCamelCase					,						__lowerCamelCase  )['''sample''']
         __A    :						Union[str, Any]						 =     (1 - alpha_prod_t_prev) ** 0.5 * model_output
         __A    :						List[Any]						 =     (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
         __A    :						Union[str, Any]						 =     sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

     return sample







 @staticmethod
 def 					UpperCamelCase__(    __lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Tuple						 =     acos(torch.dot(torch.flatten(__lowerCamelCase  )					,						torch.flatten(__lowerCamelCase  )  ) / torch.norm(__lowerCamelCase  ) / torch.norm(__lowerCamelCase  )  )
     return sin((1 - alpha) * theta  ) * xa / sin(__lowerCamelCase  ) + sin(alpha * theta  ) * xa / sin(__lowerCamelCase  )




