




"""simple docstring"""
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_				:    Union[str, Any]										=     logging.get_logger(__name__)  # pylint: disable=invalid-name

a_				:    int										=     '''
    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(      lowercase__				):




					'''simple docstring'''


					__a						:						Union[PIL.Image.Image, np.ndarray]



class __lowercase(      lowercase__				):




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a						,	__a						,	__a						,	__a						,	):
								super().__init__()

								self.register_modules(
								    prior=__a						,	image_encoder=__a						,	image_processor=__a						,	scheduler=__a						,	renderer=__a						,	)
					def     snake_case_				(    self						,	__a						,	__a						,	__a						,	__a						,	__a						,	__a     ):
								if latents is None:
											__lowerCamelCase					:	Optional[Any]	       =				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					:	str	       =				latents.to(__a     )

								__lowerCamelCase					:	Dict	       =				latents * scheduler.init_noise_sigma
								return latents
					def     snake_case_				(    self						,	__a=0     ):
								if is_accelerate_available():
											from accelerate import cpu_offload
								else:
											raise ImportError('Please install accelerate via `pip install accelerate`'     )

								__lowerCamelCase					:	Union[str, Any]	       =				torch.device(f'''cuda:{gpu_id}'''     )

								__lowerCamelCase					:	List[str]	       =				[self.image_encoder, self.prior]
								for cpu_offloaded_model in models:
											if cpu_offloaded_model is not None:
														cpu_offload(__a						,	__a     )
					@property
					def     snake_case_				(    self     ):
								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(__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     snake_case_				(    self						,	__a						,	__a						,	__a						,	__a						,	):
								if isinstance(__a						,	__a     ) and isinstance(image[0]						,	torch.Tensor     ):
											__lowerCamelCase					:	Any	       =				torch.cat(__a						,	axis=0     ) if image[0].ndim == 4 else torch.stack(__a						,	axis=0     )

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

								__lowerCamelCase					:	Optional[Any]	       =				image.to(dtype=self.image_encoder.dtype						,	device=__a     )

								__lowerCamelCase					:	Optional[int]	       =				self.image_encoder(__a     )['last_hidden_state']
								__lowerCamelCase					:	Dict	       =				image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

								__lowerCamelCase					:	str	       =				image_embeds.repeat_interleave(__a						,	dim=0     )

								if do_classifier_free_guidance:
											__lowerCamelCase					:	str	       =				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					:	List[str]	       =				torch.cat([negative_image_embeds, image_embeds]     )

								return image_embeds





					@torch.no_grad()
					@replace_example_docstring(__a     )
					def __call__(    self						,	__a						,	__a = 1						,	__a = 25						,	__a = None						,	__a = None						,	__a = 4.0						,	__a = 64						,	__a = "pil"						,	__a = True						,	):

								if isinstance(__a						,	PIL.Image.Image     ):
											__lowerCamelCase					:	List[Any]	       =				1
								elif isinstance(__a						,	torch.Tensor     ):
											__lowerCamelCase					:	Optional[int]	       =				image.shape[0]
								elif isinstance(__a						,	__a     ) and isinstance(image[0]						,	(torch.Tensor, PIL.Image.Image)     ):
											__lowerCamelCase					:	Optional[Any]	       =				len(__a     )
								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(__a     )}'''     )

								__lowerCamelCase					:	Union[str, Any]	       =				self._execution_device

								__lowerCamelCase					:	int	       =				batch_size * num_images_per_prompt

								__lowerCamelCase					:	str	       =				guidance_scale > 1.0
								__lowerCamelCase					:	Union[str, Any]	       =				self._encode_image(__a						,	__a						,	__a						,	__a     )

								# prior

								self.scheduler.set_timesteps(__a						,	device=__a     )
								__lowerCamelCase					:	List[str]	       =				self.scheduler.timesteps

								__lowerCamelCase					:	Optional[Any]	       =				self.prior.config.num_embeddings
								__lowerCamelCase					:	str	       =				self.prior.config.embedding_dim

								__lowerCamelCase					:	List[str]	       =				self.prepare_latents(
								    (batch_size, num_embeddings * embedding_dim)						,	image_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					:	Any	       =				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					:	str	       =				torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
											__lowerCamelCase					:	Union[str, Any]	       =				self.scheduler.scale_model_input(__a						,	__a     )

											__lowerCamelCase					:	str	       =				self.prior(
											    __a						,	timestep=__a						,	proj_embedding=__a						,	).predicted_image_embedding

											# remove the variance
											__lowerCamelCase       ,      __lowerCamelCase					:	int	       =				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					:	Tuple	       =				noise_pred.chunk(2     )
														__lowerCamelCase					:	Dict	       =				noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

											__lowerCamelCase					:	Tuple	       =				self.scheduler.step(
											    __a						,	timestep=__a						,	sample=__a						,	).prev_sample

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

								__lowerCamelCase					:	Optional[Any]	       =				[]
								for i, latent in enumerate(__a     ):
											print()
											__lowerCamelCase					:	Optional[int]	       =				self.renderer.decode(
											    latent[None, :]						,	__a						,	size=__a						,	ray_batch_size=4096						,	n_coarse_samples=64						,	n_fine_samples=128						,	)

											images.append(__a     )

								__lowerCamelCase					:	Dict	       =				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					:	List[Any]	       =				images.cpu().numpy()

								if output_type == "pil":
											__lowerCamelCase					:	Union[str, Any]	       =				[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     )









"""simple docstring"""
import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


a_				:    Tuple										=     '''hf-internal-testing/tiny-random-bert'''
a_				:    List[Any]										=     os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''')
a_				:    Dict										=     '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6'''

class __lowercase(      unittest.TestCase				):




					'''simple docstring'''


					def     snake_case_				(    self     ):
								__lowerCamelCase					:	List[Any]	       =				cached_file(__a						,	__a     )
								# Should have downloaded the file in here
								self.assertTrue(os.path.isdir(__a     )     )
								# Cache should contain at least those three subfolders:
								for subfolder in ["blobs", "refs", "snapshots"]:
											self.assertTrue(os.path.isdir(os.path.join(__a						,	__a     )     )     )
								with open(os.path.join(__a						,	'refs'						,	'main'     )     ) as f:
											__lowerCamelCase					:	Optional[int]	       =				f.read()
								self.assertEqual(__a						,	os.path.join(__a						,	'snapshots'						,	__a						,	__a     )     )
								self.assertTrue(os.path.isfile(__a     )     )

								# File is cached at the same place the second time.
								__lowerCamelCase					:	Optional[Any]	       =				cached_file(__a						,	__a     )
								self.assertEqual(__a						,	__a     )

								# Using a specific revision to test the full commit hash.
								__lowerCamelCase					:	Optional[int]	       =				cached_file(__a						,	__a						,	revision='9b8c223'     )
								self.assertEqual(__a						,	os.path.join(__a						,	'snapshots'						,	__a						,	__a     )     )
					def     snake_case_				(    self     ):
								with self.assertRaisesRegex(__a						,	'is not a valid model identifier'     ):
											__lowerCamelCase					:	List[str]	       =				cached_file('tiny-random-bert'						,	__a     )

								with self.assertRaisesRegex(__a						,	'is not a valid git identifier'     ):
											__lowerCamelCase					:	int	       =				cached_file(__a						,	__a						,	revision='aaaa'     )

								with self.assertRaisesRegex(__a						,	'does not appear to have a file named'     ):
											__lowerCamelCase					:	List[Any]	       =				cached_file(__a						,	'conf'     )
					def     snake_case_				(    self     ):
								with self.assertRaisesRegex(__a						,	'does not appear to have a file named'     ):
											__lowerCamelCase					:	Dict	       =				cached_file(__a						,	'conf'     )

								with open(os.path.join(__a						,	'refs'						,	'main'     )     ) as f:
											__lowerCamelCase					:	Any	       =				f.read()
								self.assertTrue(os.path.isfile(os.path.join(__a						,	'.no_exist'						,	__a						,	'conf'     )     )     )

								__lowerCamelCase					:	str	       =				cached_file(__a						,	'conf'						,	_raise_exceptions_for_missing_entries=__a     )
								self.assertIsNone(__a     )

								__lowerCamelCase					:	int	       =				cached_file(__a						,	'conf'						,	local_files_only=__a						,	_raise_exceptions_for_missing_entries=__a     )
								self.assertIsNone(__a     )

								__lowerCamelCase					:	List[str]	       =				mock.Mock()
								__lowerCamelCase					:	str	       =				500
								__lowerCamelCase					:	Union[str, Any]	       =				{}
								__lowerCamelCase					:	Dict	       =				HTTPError
								__lowerCamelCase					:	Any	       =				{}

								# Under the mock environment we get a 500 error when trying to reach the tokenizer.
								with mock.patch('requests.Session.request'						,	return_value=__a     ) as mock_head:
											__lowerCamelCase					:	Any	       =				cached_file(__a						,	'conf'						,	_raise_exceptions_for_connection_errors=__a     )
											self.assertIsNone(__a     )
											# This check we did call the fake head request
											mock_head.assert_called()
					def     snake_case_				(    self     ):
								self.assertTrue(has_file('hf-internal-testing/tiny-bert-pt-only'						,	__a     )     )
								self.assertFalse(has_file('hf-internal-testing/tiny-bert-pt-only'						,	__a     )     )
								self.assertFalse(has_file('hf-internal-testing/tiny-bert-pt-only'						,	__a     )     )
					def     snake_case_				(    self     ):
								# `get_file_from_repo` returns None if the file does not exist
								self.assertIsNone(get_file_from_repo('bert-base-cased'						,	'ahah.txt'     )     )

								# The function raises if the repository does not exist.
								with self.assertRaisesRegex(__a						,	'is not a valid model identifier'     ):
											get_file_from_repo('bert-base-case'						,	__a     )

								# The function raises if the revision does not exist.
								with self.assertRaisesRegex(__a						,	'is not a valid git identifier'     ):
											get_file_from_repo('bert-base-cased'						,	__a						,	revision='ahaha'     )

								__lowerCamelCase					:	Optional[int]	       =				get_file_from_repo('bert-base-cased'						,	__a     )
								# The name is the cached name which is not very easy to test, so instead we load the content.
								__lowerCamelCase					:	int	       =				json.loads(open(__a						,	'r'     ).read()     )
								self.assertEqual(config['hidden_size']						,	768     )





					def     snake_case_				(    self     ):
								with tempfile.TemporaryDirectory() as tmp_dir:
											__lowerCamelCase					:	int	       =				Path(__a     ) / 'a.txt'
											filename.touch()
											self.assertEqual(get_file_from_repo(__a						,	'a.txt'     )						,	str(__a     )     )

											self.assertIsNone(get_file_from_repo(__a						,	'b.txt'     )     )



