
"""simple docstring"""







from sklearn.metrics import fa_score

import datasets


lowerCamelCase__           =	"""
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
"""


lowerCamelCase__           =	"""
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.

        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'f1': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['f1'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results['f1'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")
        >>> print(round(results['f1'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'f1': array([0.8, 0. , 0. ])}
"""


lowerCamelCase__           =	"""
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,  _KWARGS_DESCRIPTION)
class 				A__ (			datasets.Metric):

		def 							__lowerCamelCase							(   self				):
			return datasets.MetricInfo(
			    description=_DESCRIPTION ,	citation=_CITATION ,	inputs_description=_KWARGS_DESCRIPTION ,	features=datasets.Features(
			        {
			            'predictions': datasets.Sequence(datasets.Value('int32'				)				),
			            'references': datasets.Sequence(datasets.Value('int32'				)				),
			        }
			        if self.config_name == 'multilabel'
			        else {
			            'predictions': datasets.Value('int32'				),
			            'references': datasets.Value('int32'				),
			        }				) ,	reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] ,	)







		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE=None ,	_SCREAMING_SNAKE_CASE=1 ,	_SCREAMING_SNAKE_CASE="binary" ,	_SCREAMING_SNAKE_CASE=None				):
			__lowerCAmelCase    :		Tuple		    =   fa_score(
			    _SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	labels=_SCREAMING_SNAKE_CASE ,	pos_label=_SCREAMING_SNAKE_CASE ,	average=_SCREAMING_SNAKE_CASE ,	sample_weight=_SCREAMING_SNAKE_CASE				)
			return {"f1": float(_SCREAMING_SNAKE_CASE				) if score.size == 1 else score}

"""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


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

lowerCamelCase__           =	"""
    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 				A__ (			_lowerCamelCase):
		A_		: Union[PIL.Image.Image, np.ndarray]




class 				A__ (			_lowerCamelCase):

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

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

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			if latents is None:
				__lowerCAmelCase    :		List[str]		    =   randn_tensor(_SCREAMING_SNAKE_CASE ,	generator=_SCREAMING_SNAKE_CASE ,	device=_SCREAMING_SNAKE_CASE ,	dtype=_SCREAMING_SNAKE_CASE				)
			else:
				if latents.shape != shape:
					raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"				)
				__lowerCAmelCase    :		Any		    =   latents.to(_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		Optional[int]		    =   latents * scheduler.init_noise_sigma
			return latents

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE=0				):
			if is_accelerate_available():
				from accelerate import cpu_offload
			else:
				raise ImportError('Please install accelerate via `pip install accelerate`'				)

			__lowerCAmelCase    :		Tuple		    =   torch.device(f"cuda:{gpu_id}"				)

			__lowerCAmelCase    :		Union[str, Any]		    =   [self.image_encoder, self.prior]
			for cpu_offloaded_model in models:
				if cpu_offloaded_model is not None:
					cpu_offload(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

		@property
		def 							__lowerCamelCase							(   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(_SCREAMING_SNAKE_CASE ,	'_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 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	):
			if isinstance(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				) and isinstance(image[0] ,	torch.Tensor				):
				__lowerCAmelCase    :		str		    =   torch.cat(_SCREAMING_SNAKE_CASE ,	axis=0				) if image[0].ndim == 4 else torch.stack(_SCREAMING_SNAKE_CASE ,	axis=0				)

			if not isinstance(_SCREAMING_SNAKE_CASE ,	torch.Tensor				):
				__lowerCAmelCase    :		Optional[int]		    =   self.image_processor(_SCREAMING_SNAKE_CASE ,	return_tensors='pt'				).pixel_values[0].unsqueeze(0				)

			__lowerCAmelCase    :		Dict		    =   image.to(dtype=self.image_encoder.dtype ,	device=_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		List[str]		    =   self.image_encoder(_SCREAMING_SNAKE_CASE				)['last_hidden_state']
			__lowerCAmelCase    :		Optional[int]		    =   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

			__lowerCAmelCase    :		Tuple		    =   image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE ,	dim=0				)

			if do_classifier_free_guidance:
				__lowerCAmelCase    :		List[Any]		    =   torch.zeros_like(_SCREAMING_SNAKE_CASE				)

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

			return image_embeds







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

			if isinstance(_SCREAMING_SNAKE_CASE ,	PIL.Image.Image				):
				__lowerCAmelCase    :		Union[str, Any]		    =   1
			elif isinstance(_SCREAMING_SNAKE_CASE ,	torch.Tensor				):
				__lowerCAmelCase    :		Tuple		    =   image.shape[0]
			elif isinstance(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				) and isinstance(image[0] ,	(torch.Tensor, PIL.Image.Image)				):
				__lowerCAmelCase    :		Any		    =   len(_SCREAMING_SNAKE_CASE				)
			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(_SCREAMING_SNAKE_CASE				)}"				)

			__lowerCAmelCase    :		Optional[Any]		    =   self._execution_device

			__lowerCAmelCase    :		Optional[Any]		    =   batch_size * num_images_per_prompt

			__lowerCAmelCase    :		Any		    =   guidance_scale > 1.0
			__lowerCAmelCase    :		List[Any]		    =   self._encode_image(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

			# prior

			self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ,	device=_SCREAMING_SNAKE_CASE				)
			__lowerCAmelCase    :		List[str]		    =   self.scheduler.timesteps

			__lowerCAmelCase    :		Optional[int]		    =   self.prior.config.num_embeddings
			__lowerCAmelCase    :		List[str]		    =   self.prior.config.embedding_dim

			__lowerCAmelCase    :		Any		    =   self.prepare_latents(
			    (batch_size, num_embeddings * embedding_dim) ,	image_embeds.dtype ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	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    :		str		    =   latents.reshape(latents.shape[0] ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

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

				__lowerCAmelCase    :		Tuple		    =   self.prior(
				    _SCREAMING_SNAKE_CASE ,	timestep=_SCREAMING_SNAKE_CASE ,	proj_embedding=_SCREAMING_SNAKE_CASE ,	).predicted_image_embedding

				# remove the variance
				__lowerCAmelCase    ,     __lowerCAmelCase    :		Tuple		    =   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    :		List[Any]		    =   noise_pred.chunk(2				)
					__lowerCAmelCase    :		Optional[int]		    =   noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

				__lowerCAmelCase    :		Dict		    =   self.scheduler.step(
				    _SCREAMING_SNAKE_CASE ,	timestep=_SCREAMING_SNAKE_CASE ,	sample=_SCREAMING_SNAKE_CASE ,	).prev_sample

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

			__lowerCAmelCase    :		List[Any]		    =   []
			for i, latent in enumerate(_SCREAMING_SNAKE_CASE				):
				print()
				__lowerCAmelCase    :		int		    =   self.renderer.decode(
				    latent[None, :] ,	_SCREAMING_SNAKE_CASE ,	size=_SCREAMING_SNAKE_CASE ,	ray_batch_size=40_96 ,	n_coarse_samples=64 ,	n_fine_samples=1_28 ,	)

				images.append(_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		List[Any]		    =   torch.stack(_SCREAMING_SNAKE_CASE				)

			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    :		int		    =   images.cpu().numpy()

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