code: 
  
  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_       :				Any		   =      logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  UpperCAmelCase_       :				List[str]		   =      '''
      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     lowerCamelCase_			(  _lowercase  ):
  	_lowercase		:      Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]
  
  
  
  
  
  
  class     lowerCamelCase_			(  _lowercase  ):
  
  
  
  
  	def __init__(				self	:    int				,			__A	:    PriorTransformer				,			__A	:    CLIPTextModelWithProjection				,			__A	:    CLIPTokenizer				,			__A	:    HeunDiscreteScheduler				,			__A	:    ShapERenderer				,			):
  		super().__init__()
  
  		self.register_modules(
  		    prior=UpperCAmelCase_				,			text_encoder=UpperCAmelCase_				,			tokenizer=UpperCAmelCase_				,			scheduler=UpperCAmelCase_				,			renderer=UpperCAmelCase_				,			)
  
  
  
  
  	def 					lowerCAmelCase_					(				self	:    Optional[Any]				,			__A	:    Any				,			__A	:    Any				,			__A	:    Optional[Any]				,			__A	:    str				,			__A	:    str				,			__A	:    List[Any]       ):
  		if latents is None:
  			__A   : Optional[Any]								= randn_tensor(UpperCAmelCase_				,			generator=UpperCAmelCase_				,			device=UpperCAmelCase_				,			dtype=UpperCAmelCase_       )
  		else:
  			if latents.shape != shape:
  				raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""       )
  			__A   : int								= latents.to(UpperCAmelCase_       )
  
  		__A   : List[str]								= latents * scheduler.init_noise_sigma
  		return latents
  
  
  
  
  	def 					lowerCAmelCase_					(				self	:    Optional[Any]				,			__A	:    str=0       ):
  		if is_accelerate_available():
  			from accelerate import cpu_offload
  		else:
  			raise ImportError("""Please install accelerate via `pip install accelerate`"""       )
  
  		__A   : str								= torch.device(F"""cuda:{gpu_id}"""       )
  
  		__A   : List[Any]								= [self.text_encoder, self.prior]
  		for cpu_offloaded_model in models:
  			if cpu_offloaded_model is not None:
  				cpu_offload(UpperCAmelCase_				,			UpperCAmelCase_       )
  
  
  
  
  	def 					lowerCAmelCase_					(				self	:    Union[str, Any]				,			__A	:    str=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."""       )
  
  		__A   : List[Any]								= torch.device(F"""cuda:{gpu_id}"""       )
  
  		if self.device.type != "cpu":
  			self.to("""cpu"""				,			silence_dtype_warnings=UpperCAmelCase_       )
  			torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)
  
  		__A   : List[Any]								= None
  		for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
  			__A   : Dict								= cpu_offload_with_hook(UpperCAmelCase_				,			UpperCAmelCase_				,			prev_module_hook=UpperCAmelCase_       )
  
  		if self.safety_checker is not None:
  			__A   : Dict								= cpu_offload_with_hook(self.safety_checker				,			UpperCAmelCase_				,			prev_module_hook=UpperCAmelCase_       )
  
  		# We'll offload the last model manually.
  		__A   : Optional[Any]								= hook
  
  
  
  
  	@property
  	def 					lowerCAmelCase_					(				self	:    Any       ):
  		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(UpperCAmelCase_				,			"""_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 					lowerCAmelCase_					(				self	:    Tuple				,			__A	:    Dict				,			__A	:    Optional[int]				,			__A	:    List[Any]				,			__A	:    Any				,			):
  		len(UpperCAmelCase_       ) if isinstance(UpperCAmelCase_				,			UpperCAmelCase_       ) else 1
  
  		# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
  		__A   : Dict								= 0
  		# get prompt text embeddings
  		__A   : List[str]								= self.tokenizer(
  		    UpperCAmelCase_				,			padding="""max_length"""				,			max_length=self.tokenizer.model_max_length				,			truncation=UpperCAmelCase_				,			return_tensors="""pt"""				,			)
  		__A   : Union[str, Any]								= text_inputs.input_ids
  		__A   : List[Any]								= self.tokenizer(UpperCAmelCase_				,			padding="""longest"""				,			return_tensors="""pt"""       ).input_ids
  
  		if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(UpperCAmelCase_				,			UpperCAmelCase_       ):
  			__A   : Union[str, 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}"""       )
  
  		__A   : Any								= self.text_encoder(text_input_ids.to(UpperCAmelCase_       )       )
  		__A   : List[str]								= text_encoder_output.text_embeds
  
  		__A   : Dict								= prompt_embeds.repeat_interleave(UpperCAmelCase_				,			dim=0       )
  		# in Shap-E it normalize the prompt_embeds and then later rescale it
  		__A   : Any								= prompt_embeds / torch.linalg.norm(UpperCAmelCase_				,			dim=-1				,			keepdim=UpperCAmelCase_       )
  
  		if do_classifier_free_guidance:
  			__A   : Optional[Any]								= torch.zeros_like(UpperCAmelCase_       )
  
  			# 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
  			__A   : Optional[Any]								= torch.cat([negative_prompt_embeds, prompt_embeds]       )
  
  		# Rescale the features to have unit variance
  		__A   : int								= math.sqrt(prompt_embeds.shape[1]       ) * prompt_embeds
  
  		return prompt_embeds
  
  
  
  
  	@torch.no_grad()
  	@replace_example_docstring(UpperCAmelCase_       )
  	def __call__(				self	:    Optional[Any]				,			__A	:    str				,			__A	:    int = 1				,			__A	:    int = 25				,			__A	:    Optional[Union[torch.Generator, List[torch.Generator]]] = None				,			__A	:    Optional[torch.FloatTensor] = None				,			__A	:    float = 4.0				,			__A	:    int = 64				,			__A	:    Optional[str] = "pil"				,			__A	:    bool = True				,			):
  
  		if isinstance(UpperCAmelCase_				,			UpperCAmelCase_       ):
  			__A   : Tuple								= 1
  		elif isinstance(UpperCAmelCase_				,			UpperCAmelCase_       ):
  			__A   : Dict								= len(UpperCAmelCase_       )
  		else:
  			raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_       )}"""       )
  
  		__A   : int								= self._execution_device
  
  		__A   : Optional[Any]								= batch_size * num_images_per_prompt
  
  		__A   : List[Any]								= guidance_scale > 1.0
  		__A   : Tuple								= self._encode_prompt(UpperCAmelCase_				,			UpperCAmelCase_				,			UpperCAmelCase_				,			UpperCAmelCase_       )
  
  		# prior
  
  		self.scheduler.set_timesteps(UpperCAmelCase_				,			device=UpperCAmelCase_       )
  		__A   : Optional[int]								= self.scheduler.timesteps
  
  		__A   : Tuple								= self.prior.config.num_embeddings
  		__A   : Any								= self.prior.config.embedding_dim
  
  		__A   : str								= self.prepare_latents(
  		    (batch_size, num_embeddings * embedding_dim)				,			prompt_embeds.dtype				,			UpperCAmelCase_				,			UpperCAmelCase_				,			UpperCAmelCase_				,			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
  		__A   : str								= latents.reshape(latents.shape[0]				,			UpperCAmelCase_				,			UpperCAmelCase_       )
  
  		for i, t in enumerate(self.progress_bar(UpperCAmelCase_       )       ):
  			# expand the latents if we are doing classifier free guidance
  			__A   : Dict								= torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents
  			__A   : str								= self.scheduler.scale_model_input(UpperCAmelCase_				,			UpperCAmelCase_       )
  
  			__A   : int								= self.prior(
  			    UpperCAmelCase_				,			timestep=UpperCAmelCase_				,			proj_embedding=UpperCAmelCase_				,			).predicted_image_embedding
  
  			# remove the variance
  			__A   : Tuple								= noise_pred.split(
  			    scaled_model_input.shape[2]				,			dim=2       )  # batch_size, num_embeddings, embedding_dim
  
  			if do_classifier_free_guidance is not None:
  				__A   : Optional[int]								= noise_pred.chunk(2       )
  				__A   : Dict								= noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
  			__A   : int								= self.scheduler.step(
  			    UpperCAmelCase_				,			timestep=UpperCAmelCase_				,			sample=UpperCAmelCase_				,			).prev_sample
  
  		if output_type == "latent":
  			return ShapEPipelineOutput(images=UpperCAmelCase_       )
  
  		__A   : Optional[Any]								= []
  		for i, latent in enumerate(UpperCAmelCase_       ):
  			__A   : int								= self.renderer.decode(
  			    latent[None, :]				,			UpperCAmelCase_				,			size=UpperCAmelCase_				,			ray_batch_size=4096				,			n_coarse_samples=64				,			n_fine_samples=128				,			)
  			images.append(UpperCAmelCase_       )
  
  		__A   : List[Any]								= torch.stack(UpperCAmelCase_       )
  
  		if output_type not in ["np", "pil"]:
  			raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}"""       )
  
  		__A   : Tuple								= images.cpu().numpy()
  
  		if output_type == "pil":
  			__A   : Optional[Any]								= [self.numpy_to_pil(UpperCAmelCase_       ) 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=UpperCAmelCase_       )
  
  
  
  
  
  
style_context: 
  
  UpperCAmelCase_       :				str		   =      [
      [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
      [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
      [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  ]
  def        __SCREAMING_SNAKE_CASE    (      a__						:      int ,a__						:      int ,a__						:      int ,a__						:      int					)				->							bool:
  	return 0 <= row < rows and 0 <= col < cols
  def        __SCREAMING_SNAKE_CASE    (      a__						:      int ,a__						:      int ,a__						:      set ,a__						:      list[list[int]]					)				->							int:
  	__A   : Union[str, Any]								= len(a__					)
  	__A   : Any								= len(mat[0]					)
  	if is_safe(a__ ,a__ ,a__ ,a__					) and (row, col) not in seen and mat[row][col] == 1:
  		seen.add((row, col)					)
  		return (
  		    1
  		    + depth_first_search(row + 1 ,a__ ,a__ ,a__					)
  		    + depth_first_search(row - 1 ,a__ ,a__ ,a__					)
  		    + depth_first_search(a__ ,col + 1 ,a__ ,a__					)
  		    + depth_first_search(a__ ,col - 1 ,a__ ,a__					)
  		)
  	else:
  		return 0
  def        __SCREAMING_SNAKE_CASE    (      a__						:      list[list[int]]					)				->							int:
  	__A   : set								= set()
  
  	__A   : Union[str, Any]								= 0
  	for row, line in enumerate(a__					):
  		for col, item in enumerate(a__					):
  			if item == 1 and (row, col) not in seen:
  				# Maximizing the area
  				__A   : Optional[Any]								= max(a__ ,depth_first_search(a__ ,a__ ,a__ ,a__					)					)
  	return max_area
  
  
  if __name__ == "__main__":
  			import doctest
  
  			print(find_max_area(matrix))  # Output -> 6
  			doctest.testmod()
  
  
  
  
  
  