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   :     Any       =				logging.get_logger(__name__)  # pylint: disable=invalid-name

A   :     Tuple       =				"\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n"


@dataclass
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  lowerCamelCase__   =  42



class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  def __init__(							self       :				str     ,   __magic_name__       :				PriorTransformer     ,   __magic_name__       :				CLIPVisionModel     ,   __magic_name__       :				CLIPImageProcessor     ,   __magic_name__       :				HeunDiscreteScheduler     ,   __magic_name__       :				ShapERenderer     ,   )     ->		int:
        super().__init__()

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







  def       __A   (							self       :				Any     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				int     ,   __magic_name__       :				str     ,   __magic_name__       :				int     ,   __magic_name__       :				Tuple     ,   __magic_name__       :				Tuple      )     ->		List[Any]:
        if latents is None:
              SCREAMING_SNAKE_CASE_      =     randn_tensor(__magic_name__     ,   generator=__magic_name__     ,   device=__magic_name__     ,   dtype=__magic_name__      )
        else:
              if latents.shape != shape:
                    raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''      )
              SCREAMING_SNAKE_CASE_      =     latents.to(__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     latents * scheduler.init_noise_sigma
        return latents







  def       __A   (							self       :				Union[str, Any]     ,   __magic_name__       :				Union[str, Any]=0      )     ->		int:
        if is_accelerate_available():
              from accelerate import cpu_offload
        else:
              raise ImportError("Please install accelerate via `pip install accelerate`"      )

        SCREAMING_SNAKE_CASE_      =     torch.device(F'''cuda:{gpu_id}'''      )

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







  @property
  def       __A   (							self       :				Optional[int]      )     ->		Tuple:
        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(__magic_name__     ,   "_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       :				List[Any]     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				Dict     ,   __magic_name__       :				List[str]     ,   )     ->		Any:
        if isinstance(__magic_name__     ,   __magic_name__      ) and isinstance(image[0]     ,   torch.Tensor      ):
              SCREAMING_SNAKE_CASE_      =     torch.cat(__magic_name__     ,   axis=0      ) if image[0].ndim == 4 else torch.stack(__magic_name__     ,   axis=0      )

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

        SCREAMING_SNAKE_CASE_      =     image.to(dtype=self.image_encoder.dtype     ,   device=__magic_name__      )

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

        SCREAMING_SNAKE_CASE_      =     image_embeds.repeat_interleave(__magic_name__     ,   dim=0      )

        if do_classifier_free_guidance:
              SCREAMING_SNAKE_CASE_      =     torch.zeros_like(__magic_name__      )

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

        return image_embeds







  @torch.no_grad()
  @replace_example_docstring(__magic_name__      )
  def __call__(							self       :				Dict     ,   __magic_name__       :				Union[PIL.Image.Image, List[PIL.Image.Image]]     ,   __magic_name__       :				int = 1     ,   __magic_name__       :				int = 25     ,   __magic_name__       :				Optional[Union[torch.Generator, List[torch.Generator]]] = None     ,   __magic_name__       :				Optional[torch.FloatTensor] = None     ,   __magic_name__       :				float = 4.0     ,   __magic_name__       :				int = 64     ,   __magic_name__       :				Optional[str] = "pil"     ,   __magic_name__       :				bool = True     ,   )     ->		Tuple:

        if isinstance(__magic_name__     ,   PIL.Image.Image      ):
              SCREAMING_SNAKE_CASE_      =     1
        elif isinstance(__magic_name__     ,   torch.Tensor      ):
              SCREAMING_SNAKE_CASE_      =     image.shape[0]
        elif isinstance(__magic_name__     ,   __magic_name__      ) and isinstance(image[0]     ,   (torch.Tensor, PIL.Image.Image)      ):
              SCREAMING_SNAKE_CASE_      =     len(__magic_name__      )
        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(__magic_name__      )}'''      )

        SCREAMING_SNAKE_CASE_      =     self._execution_device

        SCREAMING_SNAKE_CASE_      =     batch_size * num_images_per_prompt

        SCREAMING_SNAKE_CASE_      =     guidance_scale > 1.0
        SCREAMING_SNAKE_CASE_      =     self._encode_image(__magic_name__     ,   __magic_name__     ,   __magic_name__     ,   __magic_name__      )

        # prior

        self.scheduler.set_timesteps(__magic_name__     ,   device=__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     self.scheduler.timesteps

        SCREAMING_SNAKE_CASE_      =     self.prior.config.num_embeddings
        SCREAMING_SNAKE_CASE_      =     self.prior.config.embedding_dim

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

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

              SCREAMING_SNAKE_CASE_      =     self.prior(
                  __magic_name__     ,   timestep=__magic_name__     ,   proj_embedding=__magic_name__     ,   ).predicted_image_embedding

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

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

              SCREAMING_SNAKE_CASE_      =     self.scheduler.step(
                  __magic_name__     ,   timestep=__magic_name__     ,   sample=__magic_name__     ,   ).prev_sample

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

        SCREAMING_SNAKE_CASE_      =     []
        for i, latent in enumerate(__magic_name__      ):
              print()
              SCREAMING_SNAKE_CASE_      =     self.renderer.decode(
                  latent[None, :]     ,   __magic_name__     ,   size=__magic_name__     ,   ray_batch_size=4_096     ,   n_coarse_samples=64     ,   n_fine_samples=128     ,   )

              images.append(__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     torch.stack(__magic_name__      )

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

        SCREAMING_SNAKE_CASE_      =     images.cpu().numpy()

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



import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


A   :     Tuple       =				get_tests_dir("fixtures")


class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				Union[str, Any]      )     ->		Union[str, Any]:
        # A mock response for an HTTP head request to emulate server down
        SCREAMING_SNAKE_CASE_      =     mock.Mock()
        SCREAMING_SNAKE_CASE_      =     500
        SCREAMING_SNAKE_CASE_      =     {}
        SCREAMING_SNAKE_CASE_      =     HTTPError
        SCREAMING_SNAKE_CASE_      =     {}

        # Download this model to make sure it's in the cache.
        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"      )
        # Under the mock environment we get a 500 error when trying to reach the model.
        with mock.patch("requests.Session.request"     ,   return_value=__magic_name__      ) as mock_head:
              SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"      )
              # This check we did call the fake head request
              mock_head.assert_called()







  def       __A   (							self       :				Optional[int]      )     ->		Tuple:
        # This test is for deprecated behavior and can be removed in v5
        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained(
            "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"      )



@is_staging_test
class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @classmethod
  def       __A   (							cls       :				Any      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     TOKEN
        HfFolder.save_token(__magic_name__      )







  @classmethod
  def       __A   (							cls       :				int      )     ->		Optional[Any]:
        try:
              delete_repo(token=cls._token     ,   repo_id="test-feature-extractor"      )
        except HTTPError:
              pass

        try:
              delete_repo(token=cls._token     ,   repo_id="valid_org/test-feature-extractor-org"      )
        except HTTPError:
              pass

        try:
              delete_repo(token=cls._token     ,   repo_id="test-dynamic-feature-extractor"      )
        except HTTPError:
              pass







  def       __A   (							self       :				str      )     ->		List[Any]:
        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained(__magic_name__      )
        feature_extractor.push_to_hub("test-feature-extractor"     ,   use_auth_token=self._token      )

        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor'''      )
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(__magic_name__     ,   getattr(__magic_name__     ,   __magic_name__      )      )

        # Reset repo
        delete_repo(token=self._token     ,   repo_id="test-feature-extractor"      )

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  __magic_name__     ,   repo_id="test-feature-extractor"     ,   push_to_hub=__magic_name__     ,   use_auth_token=self._token      )

        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor'''      )
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(__magic_name__     ,   getattr(__magic_name__     ,   __magic_name__      )      )







  def       __A   (							self       :				Dict      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained(__magic_name__      )
        feature_extractor.push_to_hub("valid_org/test-feature-extractor"     ,   use_auth_token=self._token      )

        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor"      )
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(__magic_name__     ,   getattr(__magic_name__     ,   __magic_name__      )      )

        # Reset repo
        delete_repo(token=self._token     ,   repo_id="valid_org/test-feature-extractor"      )

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(
                  __magic_name__     ,   repo_id="valid_org/test-feature-extractor-org"     ,   push_to_hub=__magic_name__     ,   use_auth_token=self._token      )

        SCREAMING_SNAKE_CASE_      =     WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org"      )
        for k, v in feature_extractor.__dict__.items():
              self.assertEqual(__magic_name__     ,   getattr(__magic_name__     ,   __magic_name__      )      )







  def       __A   (							self       :				List[Any]      )     ->		Dict:
        CustomFeatureExtractor.register_for_auto_class()
        SCREAMING_SNAKE_CASE_      =     CustomFeatureExtractor.from_pretrained(__magic_name__      )

        feature_extractor.push_to_hub("test-dynamic-feature-extractor"     ,   use_auth_token=self._token      )

        # This has added the proper auto_map field to the config
        self.assertDictEqual(
            feature_extractor.auto_map     ,   {"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"}     ,   )

        SCREAMING_SNAKE_CASE_      =     AutoFeatureExtractor.from_pretrained(
            F'''{USER}/test-dynamic-feature-extractor'''     ,   trust_remote_code=__magic_name__      )
        # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
        self.assertEqual(new_feature_extractor.__class__.__name__     ,   "CustomFeatureExtractor"      )


