
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


SCREAMING_SNAKE_CASE__				=							logging.get_logger(__name__)  # pylint: disable=invalid-name
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class       A__  (		lowerCAmelCase__							):
							lowerCAmelCase__						:		torch.FloatTensor
							lowerCAmelCase__						:		Optional[torch.FloatTensor]            =				None






def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: Union[str, Any]       ,				SCREAMING_SNAKE_CASE			: str=0.999       ,				SCREAMING_SNAKE_CASE			: Union[str, Any]="cosine"       ,				)	->		int:
				if alpha_transform_type == "cosine":

								def alpha_bar_fn(SCREAMING_SNAKE_CASE			: List[Any]     ):
												return math.cos((t + 0.008) / 1.008 * math.pi / 2     ) ** 2

				elif alpha_transform_type == "exp":

								def alpha_bar_fn(SCREAMING_SNAKE_CASE			: str     ):
												return math.exp(t * -12.0     )

				else:
								raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}"""     )

				__lowercase								=   []
				for i in range(SCREAMING_SNAKE_CASE     ):
								__lowercase								=   i / num_diffusion_timesteps
								__lowercase								=   (i + 1) / num_diffusion_timesteps
								betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE     ) / alpha_bar_fn(SCREAMING_SNAKE_CASE     )       ,				SCREAMING_SNAKE_CASE     )     )
				return torch.tensor(SCREAMING_SNAKE_CASE       ,				dtype=torch.floataa     )
class       A__  (		lowerCAmelCase__       ,		lowerCAmelCase__							):
							lowerCAmelCase__						:		Any            =				[e.name for e in KarrasDiffusionSchedulers]
							lowerCAmelCase__						:		int            =				1





							@register_to_config
							def __init__(					self    :  List[str]	,					_UpperCAmelCase    :  int = 10_00	,					_UpperCAmelCase    :  float = 0.0_001	,					_UpperCAmelCase    :  float = 0.02	,					_UpperCAmelCase    :  str = "linear"	,					_UpperCAmelCase    :  Optional[Union[np.ndarray, List[float]]] = None	,					_UpperCAmelCase    :  str = "epsilon"	,					_UpperCAmelCase    :  str = "linear"	,					_UpperCAmelCase    :  Optional[bool] = False	,					_UpperCAmelCase    :  str = "linspace"	,					_UpperCAmelCase    :  int = 0	,					)		->						Dict:



											"""simple docstring"""


											if trained_betas is not None:
															__lowercase								=   torch.tensor(_UpperCAmelCase	,					dtype=torch.floataa							)
											elif beta_schedule == "linear":
															__lowercase								=   torch.linspace(_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					dtype=torch.floataa							)
											elif beta_schedule == "scaled_linear":
															# this schedule is very specific to the latent diffusion model.
															__lowercase								=   (
															    torch.linspace(beta_start**0.5	,					beta_end**0.5	,					_UpperCAmelCase	,					dtype=torch.floataa							) ** 2
															)
											elif beta_schedule == "squaredcos_cap_v2":
															# Glide cosine schedule
															__lowercase								=   betas_for_alpha_bar(_UpperCAmelCase							)
											else:
															raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""							)

											__lowercase								=   1.0 - self.betas
											__lowercase								=   torch.cumprod(self.alphas	,					dim=0							)

											__lowercase								=   np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5							)
											__lowercase								=   np.concatenate([sigmas[::-1], [0.0]]							).astype(np.floataa							)
											__lowercase								=   torch.from_numpy(_UpperCAmelCase							)

											# setable values
											__lowercase								=   None
											__lowercase								=   np.linspace(0	,					num_train_timesteps - 1	,					_UpperCAmelCase	,					dtype=_UpperCAmelCase							)[::-1].copy()
											__lowercase								=   torch.from_numpy(_UpperCAmelCase							)
											__lowercase								=   False
											__lowercase								=   use_karras_sigmas





							@property
							def      a__					(					self    :  List[str]							)		->						List[Any]:



											"""simple docstring"""


											if self.config.timestep_spacing in ["linspace", "trailing"]:
															return self.sigmas.max()

											return (self.sigmas.max() ** 2 + 1) ** 0.5





							def      a__					(					self    :  List[Any]	,					_UpperCAmelCase    :  torch.FloatTensor	,					_UpperCAmelCase    :  Union[float, torch.FloatTensor]							)		->						torch.FloatTensor:



											"""simple docstring"""


											if isinstance(_UpperCAmelCase	,					torch.Tensor							):
															__lowercase								=   timestep.to(self.timesteps.device							)
											__lowercase								=   (self.timesteps == timestep).nonzero().item()
											__lowercase								=   self.sigmas[step_index]

											__lowercase								=   sample / ((sigma**2 + 1) ** 0.5)

											__lowercase								=   True
											return sample





							def      a__					(					self    :  Optional[Any]	,					_UpperCAmelCase    :  int	,					_UpperCAmelCase    :  Union[str, torch.device] = None							)		->						List[str]:



											"""simple docstring"""


											__lowercase								=   num_inference_steps

											# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
											if self.config.timestep_spacing == "linspace":
															__lowercase								=   np.linspace(0	,					self.config.num_train_timesteps - 1	,					_UpperCAmelCase	,					dtype=_UpperCAmelCase							)[
															    ::-1
															].copy()
											elif self.config.timestep_spacing == "leading":
															__lowercase								=   self.config.num_train_timesteps // self.num_inference_steps
															# creates integer timesteps by multiplying by ratio
															# casting to int to avoid issues when num_inference_step is power of 3
															__lowercase								=   (np.arange(0	,					_UpperCAmelCase							) * step_ratio).round()[::-1].copy().astype(_UpperCAmelCase							)
															timesteps += self.config.steps_offset
											elif self.config.timestep_spacing == "trailing":
															__lowercase								=   self.config.num_train_timesteps / self.num_inference_steps
															# creates integer timesteps by multiplying by ratio
															# casting to int to avoid issues when num_inference_step is power of 3
															__lowercase								=   (np.arange(self.config.num_train_timesteps	,					0	,					-step_ratio							)).round().copy().astype(_UpperCAmelCase							)
															timesteps -= 1
											else:
															raise ValueError(
															    f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""							)

											__lowercase								=   np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5							)
											__lowercase								=   np.log(_UpperCAmelCase							)

											if self.config.interpolation_type == "linear":
															__lowercase								=   np.interp(_UpperCAmelCase	,					np.arange(0	,					len(_UpperCAmelCase							)							)	,					_UpperCAmelCase							)
											elif self.config.interpolation_type == "log_linear":
															__lowercase								=   torch.linspace(np.log(sigmas[-1]							)	,					np.log(sigmas[0]							)	,					num_inference_steps + 1							).exp()
											else:
															raise ValueError(
															    f"""{self.config.interpolation_type} is not implemented. Please specify interpolation_type to either"""
															    ' \'linear\' or \'log_linear\''							)

											if self.use_karras_sigmas:
															__lowercase								=   self._convert_to_karras(in_sigmas=_UpperCAmelCase	,					num_inference_steps=self.num_inference_steps							)
															__lowercase								=   np.array([self._sigma_to_t(_UpperCAmelCase	,					_UpperCAmelCase							) for sigma in sigmas]							)

											__lowercase								=   np.concatenate([sigmas, [0.0]]							).astype(np.floataa							)
											__lowercase								=   torch.from_numpy(_UpperCAmelCase							).to(device=_UpperCAmelCase							)
											if str(_UpperCAmelCase							).startswith('mps'							):
															# mps does not support float64
															__lowercase								=   torch.from_numpy(_UpperCAmelCase							).to(_UpperCAmelCase	,					dtype=torch.floataa							)
											else:
															__lowercase								=   torch.from_numpy(_UpperCAmelCase							).to(device=_UpperCAmelCase							)





							def      a__					(					self    :  Optional[Any]	,					_UpperCAmelCase    :  int	,					_UpperCAmelCase    :  Tuple							)		->						Optional[Any]:



											"""simple docstring"""


											__lowercase								=   np.log(_UpperCAmelCase							)

											# get distribution
											__lowercase								=   log_sigma - log_sigmas[:, np.newaxis]

											# get sigmas range
											__lowercase								=   np.cumsum((dists >= 0)	,					axis=0							).argmax(axis=0							).clip(max=log_sigmas.shape[0] - 2							)
											__lowercase								=   low_idx + 1

											__lowercase								=   log_sigmas[low_idx]
											__lowercase								=   log_sigmas[high_idx]

											# interpolate sigmas
											__lowercase								=   (low - log_sigma) / (low - high)
											__lowercase								=   np.clip(_UpperCAmelCase	,					0	,					1							)

											# transform interpolation to time range
											__lowercase								=   (1 - w) * low_idx + w * high_idx
											__lowercase								=   t.reshape(sigma.shape							)
											return t





							def      a__					(					self    :  List[Any]	,					_UpperCAmelCase    :  torch.FloatTensor	,					_UpperCAmelCase    :  int							)		->						torch.FloatTensor:



											"""simple docstring"""


											__lowercase								=   in_sigmas[-1].item()
											__lowercase								=   in_sigmas[0].item()

											__lowercase								=   7.0  # 7.0 is the value used in the paper
											__lowercase								=   np.linspace(0	,					1	,					_UpperCAmelCase							)
											__lowercase								=   sigma_min ** (1 / rho)
											__lowercase								=   sigma_max ** (1 / rho)
											__lowercase								=   (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
											return sigmas





							def      a__					(					self    :  str	,					_UpperCAmelCase    :  torch.FloatTensor	,					_UpperCAmelCase    :  Union[float, torch.FloatTensor]	,					_UpperCAmelCase    :  torch.FloatTensor	,					_UpperCAmelCase    :  float = 0.0	,					_UpperCAmelCase    :  float = 0.0	,					_UpperCAmelCase    :  float = float('inf'							)	,					_UpperCAmelCase    :  float = 1.0	,					_UpperCAmelCase    :  Optional[torch.Generator] = None	,					_UpperCAmelCase    :  bool = True	,					)		->						Union[EulerDiscreteSchedulerOutput, Tuple]:



											"""simple docstring"""


											if (
											    isinstance(_UpperCAmelCase	,					_UpperCAmelCase							)
											    or isinstance(_UpperCAmelCase	,					torch.IntTensor							)
											    or isinstance(_UpperCAmelCase	,					torch.LongTensor							)
											):
															raise ValueError(
															    (
															        'Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to'
															        ' `EulerDiscreteScheduler.step()` is not supported. Make sure to pass'
															        ' one of the `scheduler.timesteps` as a timestep.'
															    )	,					)

											if not self.is_scale_input_called:
															logger.warning(
															    'The `scale_model_input` function should be called before `step` to ensure correct denoising. '
															    'See `StableDiffusionPipeline` for a usage example.'							)

											if isinstance(_UpperCAmelCase	,					torch.Tensor							):
															__lowercase								=   timestep.to(self.timesteps.device							)

											__lowercase								=   (self.timesteps == timestep).nonzero().item()
											__lowercase								=   self.sigmas[step_index]

											__lowercase								=   min(s_churn / (len(self.sigmas							) - 1)	,					2**0.5 - 1							) if s_tmin <= sigma <= s_tmax else 0.0

											__lowercase								=   randn_tensor(
											    model_output.shape	,					dtype=model_output.dtype	,					device=model_output.device	,					generator=_UpperCAmelCase							)

											__lowercase								=   noise * s_noise
											__lowercase								=   sigma * (gamma + 1)

											if gamma > 0:
															__lowercase								=   sample + eps * (sigma_hat**2 - sigma**2) ** 0.5

											# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
											# NOTE: "original_sample" should not be an expected prediction_type but is left in for
											# backwards compatibility
											if self.config.prediction_type == "original_sample" or self.config.prediction_type == "sample":
															__lowercase								=   model_output
											elif self.config.prediction_type == "epsilon":
															__lowercase								=   sample - sigma_hat * model_output
											elif self.config.prediction_type == "v_prediction":
															# * c_out + input * c_skip
															__lowercase								=   model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
											else:
															raise ValueError(
															    f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""							)

											# 2. Convert to an ODE derivative
											__lowercase								=   (sample - pred_original_sample) / sigma_hat

											__lowercase								=   self.sigmas[step_index + 1] - sigma_hat

											__lowercase								=   sample + derivative * dt

											if not return_dict:
															return (prev_sample,)

											return EulerDiscreteSchedulerOutput(prev_sample=_UpperCAmelCase	,					pred_original_sample=_UpperCAmelCase							)





							def      a__					(					self    :  List[str]	,					_UpperCAmelCase    :  torch.FloatTensor	,					_UpperCAmelCase    :  torch.FloatTensor	,					_UpperCAmelCase    :  torch.FloatTensor	,					)		->						torch.FloatTensor:



											"""simple docstring"""


											__lowercase								=   self.sigmas.to(device=original_samples.device	,					dtype=original_samples.dtype							)
											if original_samples.device.type == "mps" and torch.is_floating_point(_UpperCAmelCase							):
															# mps does not support float64
															__lowercase								=   self.timesteps.to(original_samples.device	,					dtype=torch.floataa							)
															__lowercase								=   timesteps.to(original_samples.device	,					dtype=torch.floataa							)
											else:
															__lowercase								=   self.timesteps.to(original_samples.device							)
															__lowercase								=   timesteps.to(original_samples.device							)

											__lowercase								=   [(schedule_timesteps == t).nonzero().item() for t in timesteps]

											__lowercase								=   sigmas[step_indices].flatten()
											while len(sigma.shape							) < len(original_samples.shape							):
															__lowercase								=   sigma.unsqueeze(-1							)

											__lowercase								=   original_samples + noise * sigma
											return noisy_samples





							def __len__(					self    :  Any							)		->						Optional[int]:



											"""simple docstring"""


											return self.config.num_train_timesteps







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ..utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


SCREAMING_SNAKE_CASE__				=							{
    """agents""": ["""Agent""", """AzureOpenAiAgent""", """HfAgent""", """LocalAgent""", """OpenAiAgent"""],
    """base""": ["""PipelineTool""", """RemoteTool""", """Tool""", """launch_gradio_demo""", """load_tool"""],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							SCREAMING_SNAKE_CASE__				=							["""DocumentQuestionAnsweringTool"""]
							SCREAMING_SNAKE_CASE__				=							["""ImageCaptioningTool"""]
							SCREAMING_SNAKE_CASE__				=							["""ImageQuestionAnsweringTool"""]
							SCREAMING_SNAKE_CASE__				=							["""ImageSegmentationTool"""]
							SCREAMING_SNAKE_CASE__				=							["""SpeechToTextTool"""]
							SCREAMING_SNAKE_CASE__				=							["""TextClassificationTool"""]
							SCREAMING_SNAKE_CASE__				=							["""TextQuestionAnsweringTool"""]
							SCREAMING_SNAKE_CASE__				=							["""TextSummarizationTool"""]
							SCREAMING_SNAKE_CASE__				=							["""TextToSpeechTool"""]
							SCREAMING_SNAKE_CASE__				=							["""TranslationTool"""]

if TYPE_CHECKING:
							from .agents import Agent, AzureOpenAiAgent, HfAgent, LocalAgent, OpenAiAgent
							from .base import PipelineTool, RemoteTool, Tool, launch_gradio_demo, load_tool

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .document_question_answering import DocumentQuestionAnsweringTool
														from .image_captioning import ImageCaptioningTool
														from .image_question_answering import ImageQuestionAnsweringTool
														from .image_segmentation import ImageSegmentationTool
														from .speech_to_text import SpeechToTextTool
														from .text_classification import TextClassificationTool
														from .text_question_answering import TextQuestionAnsweringTool
														from .text_summarization import TextSummarizationTool
														from .text_to_speech import TextToSpeechTool
														from .translation import TranslationTool
else:
							import sys

							SCREAMING_SNAKE_CASE__				=							_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





