




"""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  UpperCAmelCase__	(snake_case__							: Optional[int]		,       snake_case__							: Union[str, Any]		,       snake_case__							: Union[str, Any]=1e-1_2   ):
  """simple docstring"""

  _snake_case							:		Any								=  jnp.divide(emb_a.T		,       jnp.clip(jnp.linalg.norm(snake_case__		,       axis=1   )		,       a_min=snake_case__   )   ).T
  _snake_case							:		Union[str, Any]								=  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  lowercase(					nn.Module			):







 '''simple docstring'''





 lowercase__			 = 42
 lowercase__			 = jnp.floataa


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  FlaxCLIPVisionModule(self.config.vision_config		)
   _snake_case							:		Tuple								=  nn.Dense(self.config.projection_dim,				use_bias=a_,				dtype=self.dtype		)

   _snake_case							:		Any								=  self.param("""concept_embeds""",				jax.nn.initializers.ones,				(17, self.config.projection_dim)		)
   _snake_case							:		List[Any]								=  self.param(
       """special_care_embeds""",				jax.nn.initializers.ones,				(3, self.config.projection_dim)		)

   _snake_case							:		Any								=  self.param("""concept_embeds_weights""",				jax.nn.initializers.ones,				(17,)		)
   _snake_case							:		int								=  self.param("""special_care_embeds_weights""",				jax.nn.initializers.ones,				(3,)		)


 def __call__(    self:		List[str],				a_:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  self.vision_model(a_		)[1]
   _snake_case							:		Union[str, Any]								=  self.visual_projection(a_		)

   _snake_case							:		Optional[Any]								=  jax_cosine_distance(a_,				self.special_care_embeds		)
   _snake_case							:		Any								=  jax_cosine_distance(a_,				self.concept_embeds		)

   # increase this value to create a stronger `nfsw` filter
   # at the cost of increasing the possibility of filtering benign image inputs
   _snake_case							:		Union[str, Any]								=  0.0

   _snake_case							:		List[Any]								=  special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
   _snake_case							:		Tuple								=  jnp.round(a_,				3		)
   _snake_case							:		int								=  jnp.any(special_scores > 0,				axis=1,				keepdims=a_		)
   # Use a lower threshold if an image has any special care concept
   _snake_case							:		int								=  is_special_care * 0.01

   _snake_case							:		List[str]								=  cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
   _snake_case							:		Optional[int]								=  jnp.round(a_,				3		)
   _snake_case							:		Dict								=  jnp.any(concept_scores > 0,				axis=1		)

   return has_nsfw_concepts







class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = CLIPConfig
 lowercase__			 = "clip_input"
 lowercase__			 = FlaxStableDiffusionSafetyCheckerModule


 def __init__(    self:		Union[str, Any],				a_:		CLIPConfig,				a_:		Optional[Tuple] = None,				a_:		int = 0,				a_:		jnp.dtype = jnp.floataa,				a_:		bool = True,				**a_:		Optional[int],				):




   '''simple docstring'''



   if input_shape is None:
     _snake_case							:		str								=  (1, 224, 224, 3)
   _snake_case							:		Tuple								=  self.module_class(config=a_,				dtype=a_,				**a_		)
   super().__init__(a_,				a_,				input_shape=a_,				seed=a_,				dtype=a_,				_do_init=_do_init		)


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		jax.random.KeyArray,				a_:		Tuple,				a_:		FrozenDict = None		):




   '''simple docstring'''



   _snake_case							:		int								=  jax.random.normal(a_,				a_		)

   _snake_case		, _snake_case							:		List[str]								=  jax.random.split(a_		)
   _snake_case							:		Optional[Any]								=  {"""params""": params_rng, """dropout""": dropout_rng}

   _snake_case							:		List[str]								=  self.module.init(a_,				a_		)["""params"""]

   return random_params


 def __call__(    self:		Tuple,				a_:		List[Any],				a_:		dict = None,				):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  jnp.transpose(a_,				(0, 2, 3, 1)		)

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








"""simple docstring"""


from typing import List, Optional, Tuple, Union

import torch

from ...utils import logging, randn_tensor
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline


A_      =    logging.get_logger(__name__)  # pylint: disable=invalid-name






class  lowercase(					__a			):







 '''simple docstring'''





 def __init__(    self:		Optional[int],				a_:		str,				a_:		Optional[Any]		):




   '''simple docstring'''



   super().__init__()
   self.register_modules(unet=a_,				scheduler=a_		)


 @torch.no_grad()
 def __call__(    self:		Any,				a_:		int = 1,				a_:		int = 100,				a_:		Optional[Union[torch.Generator, List[torch.Generator]]] = None,				a_:		Optional[float] = None,				a_:		bool = True,				):




   '''simple docstring'''



   if audio_length_in_s is None:
     _snake_case							:		Dict								=  self.unet.config.sample_size / self.unet.config.sample_rate

   _snake_case							:		Optional[int]								=  audio_length_in_s * self.unet.config.sample_rate

   _snake_case							:		int								=  2 ** len(self.unet.up_blocks		)
   if sample_size < 3 * down_scale_factor:
     raise ValueError(
         f"{audio_length_in_s} is too small. Make sure it's bigger or equal to"
         f" {3 * down_scale_factor / self.unet.config.sample_rate}."		)

   _snake_case							:		Union[str, Any]								=  int(a_		)
   if sample_size % down_scale_factor != 0:
     _snake_case							:		Optional[Any]								=  (
         (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1
     ) * down_scale_factor
     logger.info(
         f"{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled"
         f" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising"
         """ process."""		)
   _snake_case							:		str								=  int(a_		)

   _snake_case							:		int								=  next(iter(self.unet.parameters()		)		).dtype
   _snake_case							:		Optional[Any]								=  (batch_size, self.unet.config.in_channels, sample_size)
   if isinstance(a_,				a_		) and len(a_		) != batch_size:
     raise ValueError(
         f"You have passed a list of generators of length {len(a_		)}, but requested an effective batch"
         f" size of {batch_size}. Make sure the batch size matches the length of the generators."		)

   _snake_case							:		Optional[Any]								=  randn_tensor(a_,				generator=a_,				device=self.device,				dtype=a_		)

   # set step values
   self.scheduler.set_timesteps(a_,				device=audio.device		)
   _snake_case							:		Optional[int]								=  self.scheduler.timesteps.to(a_		)

   for t in self.progress_bar(self.scheduler.timesteps		):
     # 1. predict noise model_output
     _snake_case							:		str								=  self.unet(a_,				a_		).sample

     # 2. compute previous image: x_t -> t_t-1
     _snake_case							:		Optional[Any]								=  self.scheduler.step(a_,				a_,				a_		).prev_sample

   _snake_case							:		Tuple								=  audio.clamp(-1,				1		).float().cpu().numpy()

   _snake_case							:		Dict								=  audio[:, :, :original_sample_size]

   if not return_dict:
     return (audio,)

   return AudioPipelineOutput(audios=a_		)


