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
  
  
  __magic_name__	:   Any          =							logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  __magic_name__	:   Any          =							'\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")\n        ```\n'
  
  
  
  
  @dataclass
  class  __snake_case      (lowerCamelCase     ):
  							__a				   =					42
  
  
  
  
  class  __snake_case      (lowerCamelCase     ):
  
  
  
  
  							def __init__(    self:						Any    ,       A_:						PriorTransformer    ,       A_:						CLIPTextModelWithProjection    ,       A_:						CLIPTokenizer    ,       A_:						HeunDiscreteScheduler    ,       A_:						ShapERenderer    ,       ):
  										super().__init__()
  
  										self.register_modules(
  										    prior=A_    ,       text_encoder=A_    ,       tokenizer=A_    ,       scheduler=A_    ,       renderer=A_    ,       )
  
  
  
  
  							def      __a      (    self:						str    ,       A_:						Union[str, Any]    ,       A_:						Tuple    ,       A_:						Optional[Any]    ,       A_:						Optional[Any]    ,       A_:						Any    ,       A_:						Optional[int]      ):
  										if latents is None:
  													__lowerCamelCase        =			randn_tensor(A_    ,       generator=A_    ,       device=A_    ,       dtype=A_      )
  										else:
  													if latents.shape != shape:
  																raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'      )
  													__lowerCamelCase        =			latents.to(A_      )
  
  										__lowerCamelCase        =			latents * scheduler.init_noise_sigma
  										return latents
  
  
  
  
  							def      __a      (    self:						Any    ,       A_:						Union[str, Any]=0      ):
  										if is_accelerate_available():
  													from accelerate import cpu_offload
  										else:
  													raise ImportError("""Please install accelerate via `pip install accelerate`"""      )
  
  										__lowerCamelCase        =			torch.device(f'cuda:{gpu_id}'      )
  
  										__lowerCamelCase        =			[self.text_encoder, self.prior]
  										for cpu_offloaded_model in models:
  													if cpu_offloaded_model is not None:
  																cpu_offload(A_    ,       A_      )
  
  
  
  
  							def      __a      (    self:						List[Any]    ,       A_:						Dict=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        =			torch.device(f'cuda:{gpu_id}'      )
  
  										if self.device.type != "cpu":
  													self.to("""cpu"""    ,       silence_dtype_warnings=A_      )
  													torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)
  
  										__lowerCamelCase        =			None
  										for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
  													__lowerCamelCase    ,__lowerCamelCase        =			cpu_offload_with_hook(A_    ,       A_    ,       prev_module_hook=A_      )
  
  										if self.safety_checker is not None:
  													__lowerCamelCase    ,__lowerCamelCase        =			cpu_offload_with_hook(self.safety_checker    ,       A_    ,       prev_module_hook=A_      )
  
  										# We'll offload the last model manually.
  										__lowerCamelCase        =			hook
  
  
  
  
  							@property
  							def      __a      (    self:						Optional[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(A_    ,       """_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      __a      (    self:						Union[str, Any]    ,       A_:						Optional[Any]    ,       A_:						str    ,       A_:						Optional[int]    ,       A_:						Union[str, Any]    ,       ):
  										len(A_      ) if isinstance(A_    ,       A_      ) else 1
  
  										# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
  										__lowerCamelCase        =			0
  										# get prompt text embeddings
  										__lowerCamelCase        =			self.tokenizer(
  										    A_    ,       padding="""max_length"""    ,       max_length=self.tokenizer.model_max_length    ,       truncation=A_    ,       return_tensors="""pt"""    ,       )
  										__lowerCamelCase        =			text_inputs.input_ids
  										__lowerCamelCase        =			self.tokenizer(A_    ,       padding="""longest"""    ,       return_tensors="""pt"""      ).input_ids
  
  										if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(A_    ,       A_      ):
  													__lowerCamelCase        =			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        =			self.text_encoder(text_input_ids.to(A_      )      )
  										__lowerCamelCase        =			text_encoder_output.text_embeds
  
  										__lowerCamelCase        =			prompt_embeds.repeat_interleave(A_    ,       dim=0      )
  										# in Shap-E it normalize the prompt_embeds and then later rescale it
  										__lowerCamelCase        =			prompt_embeds / torch.linalg.norm(A_    ,       dim=-1    ,       keepdim=A_      )
  
  										if do_classifier_free_guidance:
  													__lowerCamelCase        =			torch.zeros_like(A_      )
  
  													# 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        =			torch.cat([negative_prompt_embeds, prompt_embeds]      )
  
  										# Rescale the features to have unit variance
  										__lowerCamelCase        =			math.sqrt(prompt_embeds.shape[1]      ) * prompt_embeds
  
  										return prompt_embeds
  
  
  
  
  							@torch.no_grad()
  							@replace_example_docstring(A_      )
  							def __call__(    self:						Tuple    ,       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(A_    ,       A_      ):
  													__lowerCamelCase        =			1
  										elif isinstance(A_    ,       A_      ):
  													__lowerCamelCase        =			len(A_      )
  										else:
  													raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(A_      )}'      )
  
  										__lowerCamelCase        =			self._execution_device
  
  										__lowerCamelCase        =			batch_size * num_images_per_prompt
  
  										__lowerCamelCase        =			guidance_scale > 1.0
  										__lowerCamelCase        =			self._encode_prompt(A_    ,       A_    ,       A_    ,       A_      )
  
  										# prior
  
  										self.scheduler.set_timesteps(A_    ,       device=A_      )
  										__lowerCamelCase        =			self.scheduler.timesteps
  
  										__lowerCamelCase        =			self.prior.config.num_embeddings
  										__lowerCamelCase        =			self.prior.config.embedding_dim
  
  										__lowerCamelCase        =			self.prepare_latents(
  										    (batch_size, num_embeddings * embedding_dim)    ,       prompt_embeds.dtype    ,       A_    ,       A_    ,       A_    ,       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        =			latents.reshape(latents.shape[0]    ,       A_    ,       A_      )
  
  										for i, t in enumerate(self.progress_bar(A_      )      ):
  													# expand the latents if we are doing classifier free guidance
  													__lowerCamelCase        =			torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
  													__lowerCamelCase        =			self.scheduler.scale_model_input(A_    ,       A_      )
  
  													__lowerCamelCase        =			self.prior(
  													    A_    ,       timestep=A_    ,       proj_embedding=A_    ,       ).predicted_image_embedding
  
  													# remove the variance
  													__lowerCamelCase    ,__lowerCamelCase        =			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        =			noise_pred.chunk(2      )
  																__lowerCamelCase        =			noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
  													__lowerCamelCase        =			self.scheduler.step(
  													    A_    ,       timestep=A_    ,       sample=A_    ,       ).prev_sample
  
  										if output_type == "latent":
  													return ShapEPipelineOutput(images=A_      )
  
  										__lowerCamelCase        =			[]
  										for i, latent in enumerate(A_      ):
  													__lowerCamelCase        =			self.renderer.decode(
  													    latent[None, :]    ,       A_    ,       size=A_    ,       ray_batch_size=40_96    ,       n_coarse_samples=64    ,       n_fine_samples=1_28    ,       )
  													images.append(A_      )
  
  										__lowerCamelCase        =			torch.stack(A_      )
  
  										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        =			images.cpu().numpy()
  
  										if output_type == "pil":
  													__lowerCamelCase        =			[self.numpy_to_pil(A_      ) 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=A_      )
  
  
  
  
  
style_context: 
  
  
  """simple docstring"""
  
  
  
  
  import unittest
  
  from transformers import load_tool
  from transformers.tools.agent_types import AGENT_TYPE_MAPPING
  
  from .test_tools_common import ToolTesterMixin, output_types
  
  
  
  
  class  __snake_case      (unittest.TestCase ,		lowerCamelCase     ):
  
  
  
  
  							def      __a      (    self:						Optional[Any]      ):
  										__lowerCamelCase        =			load_tool("""translation"""      )
  										self.tool.setup()
  										__lowerCamelCase        =			load_tool("""translation"""    ,       remote=A_      )
  
  
  
  
  							def      __a      (    self:						int      ):
  										__lowerCamelCase        =			self.tool("""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
  										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )
  
  
  
  
  							def      __a      (    self:						int      ):
  										__lowerCamelCase        =			self.remote_tool("""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
  										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )
  
  
  
  
  							def      __a      (    self:						Union[str, Any]      ):
  										__lowerCamelCase        =			self.tool(text="""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
  										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )
  
  
  
  
  							def      __a      (    self:						Any      ):
  										__lowerCamelCase        =			self.remote_tool(text="""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
  										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )
  
  
  
  
  							def      __a      (    self:						List[Any]      ):
  										__lowerCamelCase        =			["""Hey, what's up?""", """English""", """Spanish"""]
  										__lowerCamelCase        =			self.tool(*A_      )
  
  										# There is a single output
  										if len(self.tool.outputs      ) == 1:
  													__lowerCamelCase        =			[outputs]
  
  										self.assertListEqual(output_types(A_      )    ,       self.tool.outputs      )
  
  
  
  
  							def      __a      (    self:						Union[str, Any]      ):
  										__lowerCamelCase        =			["""Hey, what's up?""", """English""", """Spanish"""]
  										__lowerCamelCase        =			self.tool(*A_      )
  
  										if not isinstance(A_    ,       A_      ):
  													__lowerCamelCase        =			[outputs]
  
  										self.assertEqual(len(A_      )    ,       len(self.tool.outputs      )      )
  
  										for output, output_type in zip(A_    ,       self.tool.outputs      ):
  													__lowerCamelCase        =			AGENT_TYPE_MAPPING[output_type]
  													self.assertTrue(isinstance(A_    ,       A_      )      )
  
  
  
  
  							def      __a      (    self:						Dict      ):
  										__lowerCamelCase        =			["""Hey, what's up?""", """English""", """Spanish"""]
  
  										__lowerCamelCase        =			[]
  
  										for _input, input_type in zip(A_    ,       self.tool.inputs      ):
  													if isinstance(A_    ,       A_      ):
  																_inputs.append([AGENT_TYPE_MAPPING[_input_type](_input      ) for _input_type in input_type]      )
  													else:
  																_inputs.append(AGENT_TYPE_MAPPING[input_type](_input      )      )
  
          # Should not raise an error
  										__lowerCamelCase        =			self.tool(*A_      )
  
  										if not isinstance(A_    ,       A_      ):
  													__lowerCamelCase        =			[outputs]
  
  										self.assertEqual(len(A_      )    ,       len(self.tool.outputs      )      )
  
  
  
  
  