
'''simple docstring'''
import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand


class        SCREAMING_SNAKE_CASE__	(			snake_case_):







				@staticmethod
				def 		UpperCAmelCase_  (    A_			)->						Optional[int]:







											'''simple docstring'''






											UpperCamelCase					       =			parser.add_parser('login'		,							help='Log in using the same credentials as on huggingface.co'			)
											login_parser.set_defaults(func=lambda A_			: LoginCommand(A_			)			)
											UpperCamelCase					       =			parser.add_parser('whoami'		,							help='Find out which huggingface.co account you are logged in as.'			)
											whoami_parser.set_defaults(func=lambda A_			: WhoamiCommand(A_			)			)
											UpperCamelCase					       =			parser.add_parser('logout'		,							help='Log out'			)
											logout_parser.set_defaults(func=lambda A_			: LogoutCommand(A_			)			)

											# new system: git-based repo system
											UpperCamelCase					       =			parser.add_parser(
											    'repo'		,							help='Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'		,							)
											UpperCamelCase					       =			repo_parser.add_subparsers(
											    help='Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands'			)
											UpperCamelCase					       =			repo_subparsers.add_parser(
											    'create'		,							help='Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co'			)
											repo_create_parser.add_argument(
											    'name'		,							type=A_		,							help='Name for your model\'s repo. Will be namespaced under your username to build the model id.'		,							)
											repo_create_parser.add_argument('--organization'		,							type=A_		,							help='Optional: organization namespace.'			)
											repo_create_parser.add_argument('-y'		,							'--yes'		,							action='store_true'		,							help='Optional: answer Yes to the prompt'			)
											repo_create_parser.set_defaults(func=lambda A_			: RepoCreateCommand(A_			)			)


class        SCREAMING_SNAKE_CASE__	:
				lowerCAmelCase_			       =				"""\u001b[1m"""
				lowerCAmelCase_			       =				"""\u001b[31m"""
				lowerCAmelCase_			       =				"""\u001b[90m"""
				lowerCAmelCase_			       =				"""\u001b[0m"""







				@classmethod
				def 		UpperCAmelCase_  (    cls		,							A_			)->						Any:







											'''simple docstring'''






											return F'''{cls._bold}{s}{cls._reset}'''







				@classmethod
				def 		UpperCAmelCase_  (    cls		,							A_			)->						str:







											'''simple docstring'''






											return F'''{cls._bold}{cls._red}{s}{cls._reset}'''







				@classmethod
				def 		UpperCAmelCase_  (    cls		,							A_			)->						Any:







											'''simple docstring'''






											return F'''{cls._gray}{s}{cls._reset}'''







def 						A_(			A		:						List[List[Union[str, int]]]						,			A		:						List[str]):
							UpperCamelCase					       =			[max(len(str(A)) for x in col) for col in zip(*A						,			A)]
							UpperCamelCase					       =			('{{:{}}} ' * len(A)).format(*A)
							UpperCamelCase					       =			[]
							lines.append(row_format.format(*A))
							lines.append(row_format.format(*['-' * w for w in col_widths]))
							for row in rows:
														lines.append(row_format.format(*A))
							return "\n".join(A)


class        SCREAMING_SNAKE_CASE__	:







				def __init__(    self		,							A_			)->						Tuple:







											'''simple docstring'''






											UpperCamelCase					       =			args


class        SCREAMING_SNAKE_CASE__	(			snake_case_):







				def 		UpperCAmelCase_  (    self			)->						Dict:







											'''simple docstring'''






											print(
											    ANSI.red(
											        'ERROR! `huggingface-cli login` uses an outdated login mechanism '
											        'that is not compatible with the Hugging Face Hub backend anymore. '
											        'Please use `huggingface-cli login instead.'			)			)


class        SCREAMING_SNAKE_CASE__	(			snake_case_):







				def 		UpperCAmelCase_  (    self			)->						str:







											'''simple docstring'''






											print(
											    ANSI.red(
											        'WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '
											        '`huggingface-cli whoami` instead.'			)			)
											UpperCamelCase					       =			HfFolder.get_token()
											if token is None:
																		print('Not logged in'			)
																		exit()
											try:
																		UpperCamelCase       ,     UpperCamelCase					       =			whoami(A_			)
																		print(A_			)
																		if orgs:
																									print(ANSI.bold('orgs: '			)		,							','.join(A_			)			)
											except HTTPError as e:
																		print(A_			)
																		print(ANSI.red(e.response.text			)			)
																		exit(1			)


class        SCREAMING_SNAKE_CASE__	(			snake_case_):







				def 		UpperCAmelCase_  (    self			)->						Dict:







											'''simple docstring'''






											print(
											    ANSI.red(
											        'ERROR! `transformers-cli logout` uses an outdated logout mechanism '
											        'that is not compatible with the Hugging Face Hub backend anymore. '
											        'Please use `huggingface-cli logout instead.'			)			)


class        SCREAMING_SNAKE_CASE__	(			snake_case_):







				def 		UpperCAmelCase_  (    self			)->						str:







											'''simple docstring'''






											print(
											    ANSI.red(
											        'WARNING! Managing repositories through transformers-cli is deprecated. '
											        'Please use `huggingface-cli` instead.'			)			)
											UpperCamelCase					       =			HfFolder.get_token()
											if token is None:
																		print('Not logged in'			)
																		exit(1			)
											try:
																		UpperCamelCase					       =			subprocess.check_output(['git', '--version']			).decode('utf-8'			)
																		print(ANSI.gray(stdout.strip()			)			)
											except FileNotFoundError:
																		print('Looks like you do not have git installed, please install.'			)

											try:
																		UpperCamelCase					       =			subprocess.check_output(['git-lfs', '--version']			).decode('utf-8'			)
																		print(ANSI.gray(stdout.strip()			)			)
											except FileNotFoundError:
																		print(
																		    ANSI.red(
																		        'Looks like you do not have git-lfs installed, please install.'
																		        ' You can install from https://git-lfs.github.com/.'
																		        ' Then run `git lfs install` (you only have to do this once).'			)			)
											print(''			)

											UpperCamelCase       ,     UpperCamelCase					       =			whoami(A_			)
											UpperCamelCase					       =			self.args.organization if self.args.organization is not None else user
											UpperCamelCase					       =			F'''{namespace}/{self.args.name}'''
											print(F'''You are about to create {ANSI.bold(A_			)}'''			)

											if not self.args.yes:
																		UpperCamelCase					       =			input('Proceed? [Y/n] '			).lower()
																		if not (choice == "" or choice == "y" or choice == "yes"):
																									print('Abort'			)
																									exit()
											try:
																		UpperCamelCase					       =			create_repo(A_		,							name=self.args.name		,							organization=self.args.organization			)
											except HTTPError as e:
																		print(A_			)
																		print(ANSI.red(e.response.text			)			)
																		exit(1			)
											print('\nYour repo now lives at:'			)
											print(F'''  {ANSI.bold(A_			)}'''			)
											print('\nYou can clone it locally with the command below, and commit/push as usual.'			)
											print(F'''\n  git clone {url}'''			)
											print(''			)






'''simple docstring'''
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


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


@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class        SCREAMING_SNAKE_CASE__	(			snake_case_):
				lowerCAmelCase_			       =				42
				lowerCAmelCase_			       =				None







def 						A_(			A		:						Any						,			A		:						Optional[Any]=0.999						,			A		:						Tuple="cosine"						,			):
							if alpha_transform_type == "cosine":

														def alpha_bar_fn(A		:						Tuple):
																					return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2

							elif alpha_transform_type == "exp":

														def alpha_bar_fn(A		:						Optional[Any]):
																					return math.exp(t * -12.0)

							else:
														raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''')

							UpperCamelCase					       =			[]
							for i in range(A):
														UpperCamelCase					       =			i / num_diffusion_timesteps
														UpperCamelCase					       =			(i + 1) / num_diffusion_timesteps
														betas.append(min(1 - alpha_bar_fn(A) / alpha_bar_fn(A)						,			A))
							return torch.tensor(A						,			dtype=torch.floataa)





class        SCREAMING_SNAKE_CASE__	(			snake_case_				,    snake_case_):
				lowerCAmelCase_			       =				[e.name for e in KarrasDiffusionSchedulers]
				lowerCAmelCase_			       =				1







				@register_to_config
				def __init__(    self		,							A_ = 1000		,							A_ = 0.0_001		,							A_ = 0.02		,							A_ = "linear"		,							A_ = None		,							A_ = "epsilon"		,							A_ = "linear"		,							A_ = False		,							A_ = "linspace"		,							A_ = 0		,							)->						Optional[Any]:







											'''simple docstring'''






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

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

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

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







				@property
				def 		UpperCAmelCase_  (    self			)->						Any:







											'''simple docstring'''






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

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







				def 		UpperCAmelCase_  (    self		,							A_		,							A_			)->						torch.FloatTensor:







											'''simple docstring'''






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

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

											UpperCamelCase					       =			True
											return sample







				def 		UpperCAmelCase_  (    self		,							A_		,							A_ = None			)->						List[str]:







											'''simple docstring'''






											UpperCamelCase					       =			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":
																		UpperCamelCase					       =			np.linspace(0		,							self.config.num_train_timesteps - 1		,							A_		,							dtype=A_			)[
																		    ::-1
																		].copy()
											elif self.config.timestep_spacing == "leading":
																		UpperCamelCase					       =			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
																		UpperCamelCase					       =			(np.arange(0		,							A_			) * step_ratio).round()[::-1].copy().astype(A_			)
																		timesteps += self.config.steps_offset
											elif self.config.timestep_spacing == "trailing":
																		UpperCamelCase					       =			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
																		UpperCamelCase					       =			(np.arange(self.config.num_train_timesteps		,							0		,							-step_ratio			)).round().copy().astype(A_			)
																		timesteps -= 1
											else:
																		raise ValueError(
																		    F'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''			)

											UpperCamelCase					       =			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
											UpperCamelCase					       =			np.log(A_			)

											if self.config.interpolation_type == "linear":
																		UpperCamelCase					       =			np.interp(A_		,							np.arange(0		,							len(A_			)			)		,							A_			)
											elif self.config.interpolation_type == "log_linear":
																		UpperCamelCase					       =			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:
																		UpperCamelCase					       =			self._convert_to_karras(in_sigmas=A_		,							num_inference_steps=self.num_inference_steps			)
																		UpperCamelCase					       =			np.array([self._sigma_to_t(A_		,							A_			) for sigma in sigmas]			)

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







				def 		UpperCAmelCase_  (    self		,							A_		,							A_			)->						Union[str, Any]:







											'''simple docstring'''






											UpperCamelCase					       =			np.log(A_			)

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

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

											UpperCamelCase					       =			log_sigmas[low_idx]
											UpperCamelCase					       =			log_sigmas[high_idx]

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

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







				def 		UpperCAmelCase_  (    self		,							A_		,							A_			)->						torch.FloatTensor:







											'''simple docstring'''






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

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







				def 		UpperCAmelCase_  (    self		,							A_		,							A_		,							A_		,							A_ = 0.0		,							A_ = 0.0		,							A_ = float('inf'			)		,							A_ = 1.0		,							A_ = None		,							A_ = True		,							)->						Union[EulerDiscreteSchedulerOutput, Tuple]:







											'''simple docstring'''






											if (
											    isinstance(A_		,							A_			)
											    or isinstance(A_		,							torch.IntTensor			)
											    or isinstance(A_		,							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(A_		,							torch.Tensor			):
																		UpperCamelCase					       =			timestep.to(self.timesteps.device			)

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

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

											UpperCamelCase					       =			randn_tensor(
											    model_output.shape		,							dtype=model_output.dtype		,							device=model_output.device		,							generator=A_			)

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

											if gamma > 0:
																		UpperCamelCase					       =			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":
																		UpperCamelCase					       =			model_output
											elif self.config.prediction_type == "epsilon":
																		UpperCamelCase					       =			sample - sigma_hat * model_output
											elif self.config.prediction_type == "v_prediction":
																		# * c_out + input * c_skip
																		UpperCamelCase					       =			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
											UpperCamelCase					       =			(sample - pred_original_sample) / sigma_hat

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

											UpperCamelCase					       =			sample + derivative * dt

											if not return_dict:
																		return (prev_sample,)

											return EulerDiscreteSchedulerOutput(prev_sample=A_		,							pred_original_sample=A_			)







				def 		UpperCAmelCase_  (    self		,							A_		,							A_		,							A_		,							)->						torch.FloatTensor:







											'''simple docstring'''






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

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

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

											UpperCamelCase					       =			original_samples + noise * sigma
											return noisy_samples







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







											'''simple docstring'''






											return self.config.num_train_timesteps




