



'''simple docstring'''





from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel






@require_tf
class __A     :



 '''simple docstring'''







 __lowerCamelCase       :			List[str]		=			PegasusConfig
 __lowerCamelCase       :			Any		=			{}
 __lowerCamelCase       :			int		=			'gelu'



 def __init__(self					,  A					,  A=13					,  A=7					,  A=True					,  A=False					,  A=99					,  A=32					,  A=2					,  A=4					,  A=37					,  A=0.1					,  A=0.1					,  A=40					,  A=2					,  A=1					,  A=0					,  )       ->	Union[str, Any]:


      """simple docstring"""



      _a           =    parent
      _a           =    batch_size
      _a           =    seq_length
      _a           =    is_training
      _a           =    use_labels
      _a           =    vocab_size
      _a           =    hidden_size
      _a           =    num_hidden_layers
      _a           =    num_attention_heads
      _a           =    intermediate_size

      _a           =    hidden_dropout_prob
      _a           =    attention_probs_dropout_prob
      _a           =    max_position_embeddings
      _a           =    eos_token_id
      _a           =    pad_token_id
      _a           =    bos_token_id



 def    a__    (self			)       ->	List[Any]:


      """simple docstring"""



      _a           =    ids_tensor([self.batch_size, self.seq_length - 1]					,  self.vocab_size			)
      _a           =    tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size			)					,  1			)
      _a           =    tf.concat([input_ids, eos_tensor]					,  axis=1			)

      _a           =    ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size			)

      _a           =    self.config_cls(
          vocab_size=self.vocab_size					,  d_model=self.hidden_size					,  encoder_layers=self.num_hidden_layers					,  decoder_layers=self.num_hidden_layers					,  encoder_attention_heads=self.num_attention_heads					,  decoder_attention_heads=self.num_attention_heads					,  encoder_ffn_dim=self.intermediate_size					,  decoder_ffn_dim=self.intermediate_size					,  dropout=self.hidden_dropout_prob					,  attention_dropout=self.attention_probs_dropout_prob					,  max_position_embeddings=self.max_position_embeddings					,  eos_token_ids=[2]					,  bos_token_id=self.bos_token_id					,  pad_token_id=self.pad_token_id					,  decoder_start_token_id=self.pad_token_id					,  **self.config_updates					,  )
      _a           =    prepare_pegasus_inputs_dict(A					,  A					,  A			)
      return config, inputs_dict



 def    a__    (self					,  A					,  A			)       ->	str:


      """simple docstring"""



      _a           =    TFPegasusModel(config=A			).get_decoder()
      _a           =    inputs_dict['''input_ids''']

      _a           =    input_ids[:1, :]
      _a           =    inputs_dict['''attention_mask'''][:1, :]
      _a           =    inputs_dict['''head_mask''']
      _a           =    1

      # first forward pass
      _a           =    model(A					,  attention_mask=A					,  head_mask=A					,  use_cache=A			)

      _a    ,       _a           =    outputs.to_tuple()

      # create hypothetical next token and extent to next_input_ids
      _a           =    ids_tensor((self.batch_size, 3)					,  config.vocab_size			)
      _a           =    tf.cast(ids_tensor((self.batch_size, 3)					,  2			)					,  tf.inta			)

      # append to next input_ids and
      _a           =    tf.concat([input_ids, next_tokens]					,  axis=-1			)
      _a           =    tf.concat([attention_mask, next_attn_mask]					,  axis=-1			)

      _a           =    model(A					,  attention_mask=A			)[0]
      _a           =    model(A					,  attention_mask=A					,  past_key_values=A			)[0]

      self.parent.assertEqual(next_tokens.shape[1]					,  output_from_past.shape[1]			)

      # select random slice
      _a           =    int(ids_tensor((1,)					,  output_from_past.shape[-1]			)			)
      _a           =    output_from_no_past[:, -3:, random_slice_idx]
      _a           =    output_from_past[:, :, random_slice_idx]

      # test that outputs are equal for slice
      tf.debugging.assert_near(A					,  A					,  rtol=1E-3			)





def lowerCAmelCase    (__A    ,      __A    ,      __A    ,      __A=None    ,      __A=None    ,      __A=None    ,      __A=None    ,      __A=None    ,      ):



     """simple docstring"""



     if attention_mask is None:
          _a           =    tf.cast(tf.math.not_equal(__A    ,      config.pad_token_id)    ,      tf.inta)
     if decoder_attention_mask is None:
          _a           =    tf.concat(
              [
                  tf.ones(decoder_input_ids[:, :1].shape    ,      dtype=tf.inta),
                  tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]    ,      config.pad_token_id)    ,      tf.inta),
              ]    ,      axis=-1    ,      )
     if head_mask is None:
          _a           =    tf.ones((config.encoder_layers, config.encoder_attention_heads))
     if decoder_head_mask is None:
          _a           =    tf.ones((config.decoder_layers, config.decoder_attention_heads))
     if cross_attn_head_mask is None:
          _a           =    tf.ones((config.decoder_layers, config.decoder_attention_heads))
     return {
         "input_ids": input_ids,
         "decoder_input_ids": decoder_input_ids,
         "attention_mask": attention_mask,
         "decoder_attention_mask": decoder_attention_mask,
         "head_mask": head_mask,
         "decoder_head_mask": decoder_head_mask,
         "cross_attn_head_mask": cross_attn_head_mask,
     }






@require_tf
class __A     (    A  ,  A  ,  unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			Optional[Any]		=			(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
 __lowerCamelCase       :			Union[str, Any]		=			(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
 __lowerCamelCase       :			List[Any]		=			(
     {
         'conversational': TFPegasusForConditionalGeneration,
         'feature-extraction': TFPegasusModel,
         'summarization': TFPegasusForConditionalGeneration,
         'text2text-generation': TFPegasusForConditionalGeneration,
         'translation': TFPegasusForConditionalGeneration,
     }
     if is_tf_available()
     else {}
 )
 __lowerCamelCase       :			str		=			True
 __lowerCamelCase       :			Any		=			False
 __lowerCamelCase       :			Tuple		=			False



 def    a__    (self			)       ->	Dict:


      """simple docstring"""



      _a           =    TFPegasusModelTester(self			)
      _a           =    ConfigTester(self					,  config_class=A			)



 def    a__    (self			)       ->	Optional[int]:


      """simple docstring"""



      self.config_tester.run_common_tests()



 def    a__    (self			)       ->	Optional[Any]:


      """simple docstring"""



      _a           =    self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.check_decoder_model_past_large_inputs(*A			)






@require_sentencepiece
@require_tokenizers
@require_tf
class __A     (    unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			Optional[Any]		=			[
     ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
     ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
 ]
 __lowerCamelCase       :			Dict		=			[
     'California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'
     ' reduce the risk of wildfires.',
     'N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.',
 ]  # differs slightly from pytorch, likely due to numerical differences in linear layers
 __lowerCamelCase       :			str		=			'google/pegasus-xsum'



 @cached_property
 def    a__    (self			)       ->	Union[str, Any]:


      """simple docstring"""



      return AutoTokenizer.from_pretrained(self.model_name			)



 @cached_property
 def    a__    (self			)       ->	Tuple:


      """simple docstring"""



      _a           =    TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name			)
      return model



 def    a__    (self					,  **A			)       ->	Optional[int]:


      """simple docstring"""



      _a           =    self.translate_src_text(**A			)
      assert self.expected_text == generated_words



 def    a__    (self					,  **A			)       ->	Optional[int]:


      """simple docstring"""



      _a           =    self.tokenizer(self.src_text					,  **A					,  padding=A					,  return_tensors='''tf'''			)
      _a           =    self.model.generate(
          model_inputs.input_ids					,  attention_mask=model_inputs.attention_mask					,  num_beams=2					,  use_cache=A					,  )
      _a           =    self.tokenizer.batch_decode(generated_ids.numpy()					,  skip_special_tokens=A			)
      return generated_words



 @slow
 def    a__    (self			)       ->	int:


      """simple docstring"""



      self._assert_generated_batch_equal_expected()







from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

__a	 =      """
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""






@dataclass
class 	__lowercase					(	__snake_case	):
      UpperCamelCase										=							42






class 	__lowercase					(	__snake_case	):





      def __init__(		self    :       Any       ,							__lowerCamelCase    :       PriorTransformer       ,							__lowerCamelCase    :       CLIPVisionModel       ,							__lowerCamelCase    :       CLIPImageProcessor       ,							__lowerCamelCase    :       HeunDiscreteScheduler       ,							__lowerCamelCase    :       ShapERenderer       ,							)     -> str:






         """simple docstring"""







         super().__init__()

         self.register_modules(
             prior=__lowerCamelCase       ,							image_encoder=__lowerCamelCase       ,							image_processor=__lowerCamelCase       ,							scheduler=__lowerCamelCase       ,							renderer=__lowerCamelCase       ,							)





      def 							_lowercase					(		self    :       Dict       ,							__lowerCamelCase    :       Optional[int]       ,							__lowerCamelCase    :       Tuple       ,							__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       str       ,							__lowerCamelCase    :       str							)     -> int:






         """simple docstring"""







         if latents is None:
            UpperCAmelCase      					=  randn_tensor(__lowerCamelCase       ,							generator=__lowerCamelCase       ,							device=__lowerCamelCase       ,							dtype=__lowerCamelCase							)
         else:
            if latents.shape != shape:
               raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""							)
            UpperCAmelCase      					=  latents.to(__lowerCamelCase							)

         UpperCAmelCase      					=  latents * scheduler.init_noise_sigma
         return latents





      def 							_lowercase					(		self    :       Optional[Any]       ,							__lowerCamelCase    :       Dict=0							)     -> Optional[int]:






         """simple docstring"""







         if is_accelerate_available():
            from accelerate import cpu_offload
         else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""							)

         UpperCAmelCase      					=  torch.device(F"""cuda:{gpu_id}"""							)

         UpperCAmelCase      					=  [self.image_encoder, self.prior]
         for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
               cpu_offload(__lowerCamelCase       ,							__lowerCamelCase							)





      @property
      def 							_lowercase					(		self    :       List[str]							)     -> int:






         """simple docstring"""







         if self.device != torch.device("""meta"""							) or not hasattr(self.image_encoder       ,							"""_hf_hook"""							):
            return self.device
         for module in self.image_encoder.modules():
            if (
                hasattr(__lowerCamelCase       ,							"""_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 							_lowercase					(		self    :       List[Any]       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       List[str]       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       Union[str, Any]       ,							)     -> List[str]:






         """simple docstring"""







         if isinstance(__lowerCamelCase       ,							__lowerCamelCase							) and isinstance(image[0]       ,							torch.Tensor							):
            UpperCAmelCase      					=  torch.cat(__lowerCamelCase       ,							axis=0							) if image[0].ndim == 4 else torch.stack(__lowerCamelCase       ,							axis=0							)

         if not isinstance(__lowerCamelCase       ,							torch.Tensor							):
            UpperCAmelCase      					=  self.image_processor(__lowerCamelCase       ,							return_tensors="""pt"""							).pixel_values[0].unsqueeze(0							)

         UpperCAmelCase      					=  image.to(dtype=self.image_encoder.dtype       ,							device=__lowerCamelCase							)

         UpperCAmelCase      					=  self.image_encoder(__lowerCamelCase							)["""last_hidden_state"""]
         UpperCAmelCase      					=  image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

         UpperCAmelCase      					=  image_embeds.repeat_interleave(__lowerCamelCase       ,							dim=0							)

         if do_classifier_free_guidance:
            UpperCAmelCase      					=  torch.zeros_like(__lowerCamelCase							)

            # 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
            UpperCAmelCase      					=  torch.cat([negative_image_embeds, image_embeds]							)

         return image_embeds





      @torch.no_grad()
      @replace_example_docstring(__lowerCamelCase							)
      def __call__(		self    :       str       ,							__lowerCamelCase    :       Union[PIL.Image.Image, List[PIL.Image.Image]]       ,							__lowerCamelCase    :       int = 1       ,							__lowerCamelCase    :       int = 2_5       ,							__lowerCamelCase    :       Optional[Union[torch.Generator, List[torch.Generator]]] = None       ,							__lowerCamelCase    :       Optional[torch.FloatTensor] = None       ,							__lowerCamelCase    :       float = 4.0       ,							__lowerCamelCase    :       int = 6_4       ,							__lowerCamelCase    :       Optional[str] = "pil"       ,							__lowerCamelCase    :       bool = True       ,							)     -> Tuple:






         """simple docstring"""







         if isinstance(__lowerCamelCase       ,							PIL.Image.Image							):
            UpperCAmelCase      					=  1
         elif isinstance(__lowerCamelCase       ,							torch.Tensor							):
            UpperCAmelCase      					=  image.shape[0]
         elif isinstance(__lowerCamelCase       ,							__lowerCamelCase							) and isinstance(image[0]       ,							(torch.Tensor, PIL.Image.Image)							):
            UpperCAmelCase      					=  len(__lowerCamelCase							)
         else:
            raise ValueError(
                F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__lowerCamelCase							)}"""							)

         UpperCAmelCase      					=  self._execution_device

         UpperCAmelCase      					=  batch_size * num_images_per_prompt

         UpperCAmelCase      					=  guidance_scale > 1.0
         UpperCAmelCase      					=  self._encode_image(__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase							)

         # prior

         self.scheduler.set_timesteps(__lowerCamelCase       ,							device=__lowerCamelCase							)
         UpperCAmelCase      					=  self.scheduler.timesteps

         UpperCAmelCase      					=  self.prior.config.num_embeddings
         UpperCAmelCase      					=  self.prior.config.embedding_dim

         UpperCAmelCase      					=  self.prepare_latents(
             (batch_size, num_embeddings * embedding_dim)       ,							image_embeds.dtype       ,							__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase       ,							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
         UpperCAmelCase      					=  latents.reshape(latents.shape[0]       ,							__lowerCamelCase       ,							__lowerCamelCase							)

         for i, t in enumerate(self.progress_bar(__lowerCamelCase							)							):
            # expand the latents if we are doing classifier free guidance
            UpperCAmelCase      					=  torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
            UpperCAmelCase      					=  self.scheduler.scale_model_input(__lowerCamelCase       ,							__lowerCamelCase							)

            UpperCAmelCase      					=  self.prior(
                __lowerCamelCase       ,							timestep=__lowerCamelCase       ,							proj_embedding=__lowerCamelCase       ,							).predicted_image_embedding

            # remove the variance
            UpperCAmelCase					,	UpperCAmelCase      					=  noise_pred.split(
                scaled_model_input.shape[2]       ,							dim=2							)  # batch_size, num_embeddings, embedding_dim

            if do_classifier_free_guidance is not None:
               UpperCAmelCase					,	UpperCAmelCase      					=  noise_pred.chunk(2							)
               UpperCAmelCase      					=  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

            UpperCAmelCase      					=  self.scheduler.step(
                __lowerCamelCase       ,							timestep=__lowerCamelCase       ,							sample=__lowerCamelCase       ,							).prev_sample

         if output_type == "latent":
            return ShapEPipelineOutput(images=__lowerCamelCase							)

         UpperCAmelCase      					=  []
         for i, latent in enumerate(__lowerCamelCase							):
            print()
            UpperCAmelCase      					=  self.renderer.decode(
                latent[None, :]       ,							__lowerCamelCase       ,							size=__lowerCamelCase       ,							ray_batch_size=4_0_9_6       ,							n_coarse_samples=6_4       ,							n_fine_samples=1_2_8       ,							)

            images.append(__lowerCamelCase							)

         UpperCAmelCase      					=  torch.stack(__lowerCamelCase							)

         if output_type not in ["np", "pil"]:
            raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}"""							)

         UpperCAmelCase      					=  images.cpu().numpy()

         if output_type == "pil":
            UpperCAmelCase      					=  [self.numpy_to_pil(__lowerCamelCase							) 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=__lowerCamelCase							)



