


import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__a	 =      data_utils.TransfoXLTokenizer
__a	 =      data_utils.TransfoXLCorpus
__a	 =      data_utils
__a	 =      data_utils
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Dict:
   if transfo_xl_dataset_file:
      # Convert a pre-processed corpus (see original TensorFlow repo)
      with open(lowerCAmelCase_	,    """rb""" ) as fp:
         UpperCAmelCase      					=  pickle.load(lowerCAmelCase_	,    encoding="""latin1""" )
      # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
      UpperCAmelCase      					=  pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""]
      print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
      UpperCAmelCase      					=  corpus.vocab.__dict__
      torch.save(lowerCAmelCase_	,    lowerCAmelCase_ )

      UpperCAmelCase      					=  corpus.__dict__
      corpus_dict_no_vocab.pop("""vocab"""	,    lowerCAmelCase_ )
      UpperCAmelCase      					=  pytorch_dump_folder_path + """/""" + CORPUS_NAME
      print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
      torch.save(lowerCAmelCase_	,    lowerCAmelCase_ )

   if tf_checkpoint_path:
      # Convert a pre-trained TensorFlow model
      UpperCAmelCase      					=  os.path.abspath(lowerCAmelCase_ )
      UpperCAmelCase      					=  os.path.abspath(lowerCAmelCase_ )

      print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
      # Initialise PyTorch model
      if transfo_xl_config_file == "":
         UpperCAmelCase      					=  TransfoXLConfig()
      else:
         UpperCAmelCase      					=  TransfoXLConfig.from_json_file(lowerCAmelCase_ )
      print(F"""Building PyTorch model from configuration: {config}""" )
      UpperCAmelCase      					=  TransfoXLLMHeadModel(lowerCAmelCase_ )

      UpperCAmelCase      					=  load_tf_weights_in_transfo_xl(lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )
      # Save pytorch-model
      UpperCAmelCase      					=  os.path.join(lowerCAmelCase_	,    lowerCAmelCase_ )
      UpperCAmelCase      					=  os.path.join(lowerCAmelCase_	,    lowerCAmelCase_ )
      print(F"""Save PyTorch model to {os.path.abspath(lowerCAmelCase_ )}""" )
      torch.save(model.state_dict()	,    lowerCAmelCase_ )
      print(F"""Save configuration file to {os.path.abspath(lowerCAmelCase_ )}""" )
      with open(lowerCAmelCase_	,    """w"""	,    encoding="""utf-8""" ) as f:
         f.write(config.to_json_string() )


if __name__ == "__main__":
 __a	 =      argparse.ArgumentParser()
 parser.add_argument(
     """--pytorch_dump_folder_path""",
     default=None,
     type=str,
     required=True,
     help="""Path to the folder to store the PyTorch model or dataset/vocab.""",
 )
 parser.add_argument(
     """--tf_checkpoint_path""",
     default="""""",
     type=str,
     help="""An optional path to a TensorFlow checkpoint path to be converted.""",
 )
 parser.add_argument(
     """--transfo_xl_config_file""",
     default="""""",
     type=str,
     help=(
         """An optional config json file corresponding to the pre-trained BERT model. \n"""
         """This specifies the model architecture."""
     ),
 )
 parser.add_argument(
     """--transfo_xl_dataset_file""",
     default="""""",
     type=str,
     help="""An optional dataset file to be converted in a vocabulary.""",
 )
 __a	 =      parser.parse_args()
 convert_transfo_xl_checkpoint_to_pytorch(
     args.tf_checkpoint_path,
     args.transfo_xl_config_file,
     args.pytorch_dump_folder_path,
     args.transfo_xl_dataset_file,
 )







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							)



