code: 
  '''simple docstring'''
  
  import math
  from dataclasses import dataclass
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  import torch
  from transformers import CLIPTextModelWithProjection, CLIPTokenizer
  
  from ...models import PriorTransformer
  from ...pipelines import DiffusionPipeline
  from ...schedulers import HeunDiscreteScheduler
  from ...utils import (
      BaseOutput,
      is_accelerate_available,
      is_accelerate_version,
      logging,
      randn_tensor,
      replace_example_docstring,
  )
  from .renderer import ShapERenderer
  
  
  UpperCamelCase_     			=       logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  UpperCamelCase_     			=       """
      Examples:
          ```py
          >>> import torch
          >>> from diffusers import DiffusionPipeline
          >>> from diffusers.utils import export_to_gif
  
          >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")
  
          >>> repo = \"openai/shap-e\"
          >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
          >>> pipe = pipe.to(device)
  
          >>> guidance_scale = 15.0
          >>> prompt = \"a shark\"
  
          >>> images = pipe(
          ...     prompt,
          ...     guidance_scale=guidance_scale,
          ...     num_inference_steps=64,
          ...     frame_size=256,
          ... ).images
  
          >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
          ```
  """
  
  
  @dataclass
  class   a_  (_a    ):
         __lowerCAmelCase    :				Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]
  
  
  
  class   a_  (_a    ):
  
  
  
  
         def __init__(     self   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   ):
           super().__init__()
  
           self.register_modules(
               prior=snake_case_   ,   text_encoder=snake_case_   ,   tokenizer=snake_case_   ,   scheduler=snake_case_   ,   renderer=snake_case_   ,   )
  
  
  
  
         def 							__UpperCamelCase       (     self   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_  ):
           if latents is None:
             _lowerCAmelCase       :  Tuple   				=					randn_tensor(snake_case_   ,   generator=snake_case_   ,   device=snake_case_   ,   dtype=snake_case_  )
           else:
             if latents.shape != shape:
               raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'  )
             _lowerCAmelCase       :  int   				=					latents.to(snake_case_  )
  
           _lowerCAmelCase       :  Tuple   				=					latents * scheduler.init_noise_sigma
           return latents
  
  
  
  
         def 							__UpperCamelCase       (     self   ,   snake_case_=0  ):
           if is_accelerate_available():
             from accelerate import cpu_offload
           else:
             raise ImportError("""Please install accelerate via `pip install accelerate`"""  )
  
           _lowerCAmelCase       :  str   				=					torch.device(f'cuda:{gpu_id}'  )
  
           _lowerCAmelCase       :  Optional[Any]   				=					[self.text_encoder, self.prior]
           for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
               cpu_offload(snake_case_   ,   snake_case_  )
  
  
  
  
         def 							__UpperCamelCase       (     self   ,   snake_case_=0  ):
           if is_accelerate_available() and is_accelerate_version(""">="""   ,   """0.17.0.dev0"""  ):
             from accelerate import cpu_offload_with_hook
           else:
             raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""  )
  
           _lowerCAmelCase       :  int   				=					torch.device(f'cuda:{gpu_id}'  )
  
           if self.device.type != "cpu":
             self.to("""cpu"""   ,   silence_dtype_warnings=snake_case_  )
             torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)
  
           _lowerCAmelCase       :  Optional[Any]   				=					None
           for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
             _lowerCAmelCase				,					_lowerCAmelCase       :  Optional[Any]   				=					cpu_offload_with_hook(snake_case_   ,   snake_case_   ,   prev_module_hook=snake_case_  )
  
           if self.safety_checker is not None:
             _lowerCAmelCase				,					_lowerCAmelCase       :  Any   				=					cpu_offload_with_hook(self.safety_checker   ,   snake_case_   ,   prev_module_hook=snake_case_  )
  
           # We'll offload the last model manually.
           _lowerCAmelCase       :  Union[str, Any]   				=					hook
  
  
  
  
         @property
         def 							__UpperCamelCase       (     self  ):
           if self.device != torch.device("""meta"""  ) or not hasattr(self.text_encoder   ,   """_hf_hook"""  ):
             return self.device
           for module in self.text_encoder.modules():
             if (
                 hasattr(snake_case_   ,   """_hf_hook"""  )
                 and hasattr(module._hf_hook   ,   """execution_device"""  )
                 and module._hf_hook.execution_device is not None
             ):
               return torch.device(module._hf_hook.execution_device  )
           return self.device
  
  
  
  
         def 							__UpperCamelCase       (     self   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   ):
           len(snake_case_  ) if isinstance(snake_case_   ,   snake_case_  ) else 1
  
           # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
           _lowerCAmelCase       :  List[str]   				=					0
           # get prompt text embeddings
           _lowerCAmelCase       :  str   				=					self.tokenizer(
               snake_case_   ,   padding="""max_length"""   ,   max_length=self.tokenizer.model_max_length   ,   truncation=snake_case_   ,   return_tensors="""pt"""   ,   )
           _lowerCAmelCase       :  Optional[int]   				=					text_inputs.input_ids
           _lowerCAmelCase       :  Tuple   				=					self.tokenizer(snake_case_   ,   padding="""longest"""   ,   return_tensors="""pt"""  ).input_ids
  
           if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(snake_case_   ,   snake_case_  ):
             _lowerCAmelCase       :  Optional[Any]   				=					self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]  )
             logger.warning(
                 """The following part of your input was truncated because CLIP can only handle sequences up to"""
                 f' {self.tokenizer.model_max_length} tokens: {removed_text}'  )
  
           _lowerCAmelCase       :  int   				=					self.text_encoder(text_input_ids.to(snake_case_  )  )
           _lowerCAmelCase       :  Dict   				=					text_encoder_output.text_embeds
  
           _lowerCAmelCase       :  Dict   				=					prompt_embeds.repeat_interleave(snake_case_   ,   dim=0  )
           # in Shap-E it normalize the prompt_embeds and then later rescale it
           _lowerCAmelCase       :  str   				=					prompt_embeds / torch.linalg.norm(snake_case_   ,   dim=-1   ,   keepdim=snake_case_  )
  
           if do_classifier_free_guidance:
             _lowerCAmelCase       :  Optional[int]   				=					torch.zeros_like(snake_case_  )
  
             # For classifier free guidance, we need to do two forward passes.
             # Here we concatenate the unconditional and text embeddings into a single batch
             # to avoid doing two forward passes
             _lowerCAmelCase       :  int   				=					torch.cat([negative_prompt_embeds, prompt_embeds]  )
  
           # Rescale the features to have unit variance
           _lowerCAmelCase       :  Union[str, Any]   				=					math.sqrt(prompt_embeds.shape[1]  ) * prompt_embeds
  
           return prompt_embeds
  
  
  
  
  
  
  
         @torch.no_grad()
         @replace_example_docstring(snake_case_  )
         def __call__(     self   ,   snake_case_   ,   snake_case_ = 1   ,   snake_case_ = 2_5   ,   snake_case_ = None   ,   snake_case_ = None   ,   snake_case_ = 4.0   ,   snake_case_ = 6_4   ,   snake_case_ = "pil"   ,   snake_case_ = True   ,   ):
  
           if isinstance(snake_case_   ,   snake_case_  ):
             _lowerCAmelCase       :  Union[str, Any]   				=					1
           elif isinstance(snake_case_   ,   snake_case_  ):
             _lowerCAmelCase       :  Dict   				=					len(snake_case_  )
           else:
             raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(snake_case_  )}'  )
  
           _lowerCAmelCase       :  Dict   				=					self._execution_device
  
           _lowerCAmelCase       :  List[Any]   				=					batch_size * num_images_per_prompt
  
           _lowerCAmelCase       :  int   				=					guidance_scale > 1.0
           _lowerCAmelCase       :  Any   				=					self._encode_prompt(snake_case_   ,   snake_case_   ,   snake_case_   ,   snake_case_  )
  
           # prior
  
           self.scheduler.set_timesteps(snake_case_   ,   device=snake_case_  )
           _lowerCAmelCase       :  List[Any]   				=					self.scheduler.timesteps
  
           _lowerCAmelCase       :  Any   				=					self.prior.config.num_embeddings
           _lowerCAmelCase       :  Tuple   				=					self.prior.config.embedding_dim
  
           _lowerCAmelCase       :  Tuple   				=					self.prepare_latents(
               (batch_size, num_embeddings * embedding_dim)   ,   prompt_embeds.dtype   ,   snake_case_   ,   snake_case_   ,   snake_case_   ,   self.scheduler   ,   )
  
           # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
           _lowerCAmelCase       :  List[str]   				=					latents.reshape(latents.shape[0]   ,   snake_case_   ,   snake_case_  )
  
           for i, t in enumerate(self.progress_bar(snake_case_  )  ):
             # expand the latents if we are doing classifier free guidance
             _lowerCAmelCase       :  Union[str, Any]   				=					torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents
             _lowerCAmelCase       :  Optional[Any]   				=					self.scheduler.scale_model_input(snake_case_   ,   snake_case_  )
  
             _lowerCAmelCase       :  Tuple   				=					self.prior(
                 snake_case_   ,   timestep=snake_case_   ,   proj_embedding=snake_case_   ,   ).predicted_image_embedding
  
             # remove the variance
             _lowerCAmelCase				,					_lowerCAmelCase       :  Optional[int]   				=					noise_pred.split(
                 scaled_model_input.shape[2]   ,   dim=2  )  # batch_size, num_embeddings, embedding_dim
  
             if do_classifier_free_guidance is not None:
               _lowerCAmelCase				,					_lowerCAmelCase       :  List[Any]   				=					noise_pred.chunk(2  )
               _lowerCAmelCase       :  Union[str, Any]   				=					noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
             _lowerCAmelCase       :  Optional[Any]   				=					self.scheduler.step(
                 snake_case_   ,   timestep=snake_case_   ,   sample=snake_case_   ,   ).prev_sample
  
           if output_type == "latent":
             return ShapEPipelineOutput(images=snake_case_  )
  
           _lowerCAmelCase       :  Optional[Any]   				=					[]
           for i, latent in enumerate(snake_case_  ):
             _lowerCAmelCase       :  str   				=					self.renderer.decode(
                 latent[None, :]   ,   snake_case_   ,   size=snake_case_   ,   ray_batch_size=4_0_9_6   ,   n_coarse_samples=6_4   ,   n_fine_samples=1_2_8   ,   )
             images.append(snake_case_  )
  
           _lowerCAmelCase       :  int   				=					torch.stack(snake_case_  )
  
           if output_type not in ["np", "pil"]:
             raise ValueError(f'Only the output types `pil` and `np` are supported not output_type={output_type}'  )
  
           _lowerCAmelCase       :  Tuple   				=					images.cpu().numpy()
  
           if output_type == "pil":
             _lowerCAmelCase       :  Optional[int]   				=					[self.numpy_to_pil(snake_case_  ) for image in images]
  
           # Offload last model to CPU
           if hasattr(self   ,   """final_offload_hook"""  ) and self.final_offload_hook is not None:
             self.final_offload_hook.offload()
  
           if not return_dict:
             return (images,)
  
           return ShapEPipelineOutput(images=snake_case_  )
  
  
  
style_context: 
  '''simple docstring'''
  
  from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
  from numpy import divide, inta, multiply, ravel, sort, zeros_like
  
  
  def 	_UpperCAmelCase				(  _lowerCamelCase						:       str  ,      _lowerCamelCase						:       List[Any]=3		)    ->						Union[str, Any]:
    _lowerCAmelCase       :  str   				=					int(mask / 2		)
    # copy image size
    _lowerCAmelCase       :  Dict   				=					zeros_like(_lowerCamelCase		)
    for i in range(_lowerCamelCase  ,      gray_img.shape[0] - bd		):
      for j in range(_lowerCamelCase  ,      gray_img.shape[1] - bd		):
        # get mask according with mask
        _lowerCAmelCase       :  Union[str, Any]   				=					ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]		)
        # calculate mask median
        _lowerCAmelCase       :  str   				=					sort(_lowerCamelCase		)[inta(divide((multiply(_lowerCamelCase  ,      _lowerCamelCase		))  ,      2		) + 1		)]
        _lowerCAmelCase       :  Dict   				=					median
    return median_img
  
  
  if __name__ == "__main__":
       # read original image
       UpperCamelCase_     			=       imread("""../image_data/lena.jpg""")
       # turn image in gray scale value
       UpperCamelCase_     			=       cvtColor(img, COLOR_BGR2GRAY)
  
       # get values with two different mask size
       UpperCamelCase_     			=       median_filter(gray, 3)
       UpperCamelCase_     			=       median_filter(gray, 5)
  
       # show result images
       imshow("""median filter with 3x3 mask""", medianaxa)
       imshow("""median filter with 5x5 mask""", medianaxa)
       waitKey(0)
  
  
  