


import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow


class     __UpperCAmelCase							:


     """simple docstring"""


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A    ):
        return None







class     __UpperCAmelCase							:


     """simple docstring"""


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A  ,       __A    ):
        return None







class     __UpperCAmelCase							(       unittest.TestCase							):


     """simple docstring"""
     _lowerCamelCase   =      [
         # (model_name, model_kwargs)
         ("""bert-base-cased""", {}),
         ("""gpt2""", {"""use_cache""": False}),  # We don't support exporting GPT2 past keys anymore
     ]


     @require_tf
     @slow
     def 	snake_case_  (	self    ):
        for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           self._test_export(__A  ,       """tf"""  ,       12  ,       **__A    )


     @require_torch
     @slow
     def 	snake_case_  (	self    ):
        for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           self._test_export(__A  ,       """pt"""  ,       12  ,       **__A    )


     @require_torch
     @slow
     def 	snake_case_  (	self    ):
        from transformers import BertModel

        __a					=  ["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""]
        with NamedTemporaryFile(mode="""w+t"""    ) as vocab_file:
           vocab_file.write("""\n""".join(__A    )    )
           vocab_file.flush()
           __a					=  BertTokenizerFast(vocab_file.name    )

        with TemporaryDirectory() as bert_save_dir:
           __a					=  BertModel(BertConfig(vocab_size=len(__A    )    )    )
           model.save_pretrained(__A    )
           self._test_export(__A  ,       """pt"""  ,       12  ,       __A    )


     @require_tf
     @slow
     def 	snake_case_  (	self    ):
        for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           __a					=  self._test_export(__A  ,       """tf"""  ,       12  ,       **__A    )
           __a					=  quantize(Path(__A    )    )

           # Ensure the actual quantized model is not bigger than the original one
           if quantized_path.stat().st_size >= Path(__A    ).stat().st_size:
              self.fail("""Quantized model is bigger than initial ONNX model"""    )


     @require_torch
     @slow
     def 	snake_case_  (	self    ):
        for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
           __a					=  self._test_export(__A  ,       """pt"""  ,       12  ,       **__A    )
           __a					=  quantize(__A    )

           # Ensure the actual quantized model is not bigger than the original one
           if quantized_path.stat().st_size >= Path(__A    ).stat().st_size:
              self.fail("""Quantized model is bigger than initial ONNX model"""    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A  ,       __A=None  ,       **__A    ):
        try:
           # Compute path
           with TemporaryDirectory() as tempdir:
              __a					=  Path(__A    ).joinpath("""model.onnx"""    )

           # Remove folder if exists
           if path.parent.exists():
              path.parent.rmdir()

           # Export
           convert(__A  ,       __A  ,       __A  ,       __A  ,       __A  ,       **__A    )

           return path
        except Exception as e:
           self.fail(__A    )


     @require_torch
     @require_tokenizers
     @slow
     def 	snake_case_  (	self    ):
        from transformers import BertModel

        __a					=  BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""    )    )
        __a					=  BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""    )
        self._test_infer_dynamic_axis(__A  ,       __A  ,       """pt"""    )


     @require_tf
     @require_tokenizers
     @slow
     def 	snake_case_  (	self    ):
        from transformers import TFBertModel

        __a					=  TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random"""    )    )
        __a					=  BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random"""    )
        self._test_infer_dynamic_axis(__A  ,       __A  ,       """tf"""    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A    ):
        __a					=  FeatureExtractionPipeline(__A  ,       __A    )

        __a					=  ["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""]
        __a	,    __a	,    __a	,    __a					=  infer_shapes(__A  ,       __A    )

        # Assert all variables are present
        self.assertEqual(len(__A    )  ,       len(__A    )    )
        self.assertTrue(all(var_name in shapes for var_name in variable_names    )    )
        self.assertSequenceEqual(variable_names[:3]  ,       __A    )
        self.assertSequenceEqual(variable_names[3:]  ,       __A    )

        # Assert inputs are {0: batch, 1: sequence}
        for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
           self.assertDictEqual(shapes[var_name]  ,       {0: """batch""", 1: """sequence"""}    )

        # Assert outputs are {0: batch, 1: sequence} and {0: batch}
        self.assertDictEqual(shapes["""output_0"""]  ,       {0: """batch""", 1: """sequence"""}    )
        self.assertDictEqual(shapes["""output_1"""]  ,       {0: """batch"""}    )


     def 	snake_case_  (	self    ):
        __a					=  ["""input_ids""", """attention_mask""", """token_type_ids"""]
        __a					=  {"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]}
        __a	,    __a					=  ensure_valid_input(FuncContiguousArgs()  ,       __A  ,       __A    )

        # Should have exactly the same number of args (all are valid)
        self.assertEqual(len(__A    )  ,       3    )

        # Should have exactly the same input names
        self.assertEqual(set(__A    )  ,       set(__A    )    )

        # Parameter should be reordered according to their respective place in the function:
        # (input_ids, token_type_ids, attention_mask)
        self.assertEqual(__A  ,       (tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""])    )

        # Generated args are interleaved with another args (for instance parameter "past" in GPT2)
        __a	,    __a					=  ensure_valid_input(FuncNonContiguousArgs()  ,       __A  ,       __A    )

        # Should have exactly the one arg (all before the one not provided "some_other_args")
        self.assertEqual(len(__A    )  ,       1    )
        self.assertEqual(len(__A    )  ,       1    )

        # Should have only "input_ids"
        self.assertEqual(inputs_args[0]  ,       tokens["""input_ids"""]    )
        self.assertEqual(ordered_input_names[0]  ,       """input_ids"""    )


     def 	snake_case_  (	self    ):
        __a					=  generate_identified_filename(Path("""/home/something/my_fake_model.onnx"""    )  ,       """-test"""    )
        self.assertEqual("""/home/something/my_fake_model-test.onnx"""  ,       generated.as_posix()    )







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							)



