

'''simple docstring'''






import os

import requests

snake_case_       =       'https://www.amdoren.com/api/currency.php'


# Currency and their description
snake_case_       =       '\nAED	United Arab Emirates Dirham\nAFN	Afghan Afghani\nALL	Albanian Lek\nAMD	Armenian Dram\nANG	Netherlands Antillean Guilder\nAOA	Angolan Kwanza\nARS	Argentine Peso\nAUD	Australian Dollar\nAWG	Aruban Florin\nAZN	Azerbaijani Manat\nBAM	Bosnia & Herzegovina Convertible Mark\nBBD	Barbadian Dollar\nBDT	Bangladeshi Taka\nBGN	Bulgarian Lev\nBHD	Bahraini Dinar\nBIF	Burundian Franc\nBMD	Bermudian Dollar\nBND	Brunei Dollar\nBOB	Bolivian Boliviano\nBRL	Brazilian Real\nBSD	Bahamian Dollar\nBTN	Bhutanese Ngultrum\nBWP	Botswana Pula\nBYN	Belarus Ruble\nBZD	Belize Dollar\nCAD	Canadian Dollar\nCDF	Congolese Franc\nCHF	Swiss Franc\nCLP	Chilean Peso\nCNY	Chinese Yuan\nCOP	Colombian Peso\nCRC	Costa Rican Colon\nCUC	Cuban Convertible Peso\nCVE	Cape Verdean Escudo\nCZK	Czech Republic Koruna\nDJF	Djiboutian Franc\nDKK	Danish Krone\nDOP	Dominican Peso\nDZD	Algerian Dinar\nEGP	Egyptian Pound\nERN	Eritrean Nakfa\nETB	Ethiopian Birr\nEUR	Euro\nFJD	Fiji Dollar\nGBP	British Pound Sterling\nGEL	Georgian Lari\nGHS	Ghanaian Cedi\nGIP	Gibraltar Pound\nGMD	Gambian Dalasi\nGNF	Guinea Franc\nGTQ	Guatemalan Quetzal\nGYD	Guyanaese Dollar\nHKD	Hong Kong Dollar\nHNL	Honduran Lempira\nHRK	Croatian Kuna\nHTG	Haiti Gourde\nHUF	Hungarian Forint\nIDR	Indonesian Rupiah\nILS	Israeli Shekel\nINR	Indian Rupee\nIQD	Iraqi Dinar\nIRR	Iranian Rial\nISK	Icelandic Krona\nJMD	Jamaican Dollar\nJOD	Jordanian Dinar\nJPY	Japanese Yen\nKES	Kenyan Shilling\nKGS	Kyrgystani Som\nKHR	Cambodian Riel\nKMF	Comorian Franc\nKPW	North Korean Won\nKRW	South Korean Won\nKWD	Kuwaiti Dinar\nKYD	Cayman Islands Dollar\nKZT	Kazakhstan Tenge\nLAK	Laotian Kip\nLBP	Lebanese Pound\nLKR	Sri Lankan Rupee\nLRD	Liberian Dollar\nLSL	Lesotho Loti\nLYD	Libyan Dinar\nMAD	Moroccan Dirham\nMDL	Moldovan Leu\nMGA	Malagasy Ariary\nMKD	Macedonian Denar\nMMK	Myanma Kyat\nMNT	Mongolian Tugrik\nMOP	Macau Pataca\nMRO	Mauritanian Ouguiya\nMUR	Mauritian Rupee\nMVR	Maldivian Rufiyaa\nMWK	Malawi Kwacha\nMXN	Mexican Peso\nMYR	Malaysian Ringgit\nMZN	Mozambican Metical\nNAD	Namibian Dollar\nNGN	Nigerian Naira\nNIO	Nicaragua Cordoba\nNOK	Norwegian Krone\nNPR	Nepalese Rupee\nNZD	New Zealand Dollar\nOMR	Omani Rial\nPAB	Panamanian Balboa\nPEN	Peruvian Nuevo Sol\nPGK	Papua New Guinean Kina\nPHP	Philippine Peso\nPKR	Pakistani Rupee\nPLN	Polish Zloty\nPYG	Paraguayan Guarani\nQAR	Qatari Riyal\nRON	Romanian Leu\nRSD	Serbian Dinar\nRUB	Russian Ruble\nRWF	Rwanda Franc\nSAR	Saudi Riyal\nSBD	Solomon Islands Dollar\nSCR	Seychellois Rupee\nSDG	Sudanese Pound\nSEK	Swedish Krona\nSGD	Singapore Dollar\nSHP	Saint Helena Pound\nSLL	Sierra Leonean Leone\nSOS	Somali Shilling\nSRD	Surinamese Dollar\nSSP	South Sudanese Pound\nSTD	Sao Tome and Principe Dobra\nSYP	Syrian Pound\nSZL	Swazi Lilangeni\nTHB	Thai Baht\nTJS	Tajikistan Somoni\nTMT	Turkmenistani Manat\nTND	Tunisian Dinar\nTOP	Tonga Paanga\nTRY	Turkish Lira\nTTD	Trinidad and Tobago Dollar\nTWD	New Taiwan Dollar\nTZS	Tanzanian Shilling\nUAH	Ukrainian Hryvnia\nUGX	Ugandan Shilling\nUSD	United States Dollar\nUYU	Uruguayan Peso\nUZS	Uzbekistan Som\nVEF	Venezuelan Bolivar\nVND	Vietnamese Dong\nVUV	Vanuatu Vatu\nWST	Samoan Tala\nXAF	Central African CFA franc\nXCD	East Caribbean Dollar\nXOF	West African CFA franc\nXPF	CFP Franc\nYER	Yemeni Rial\nZAR	South African Rand\nZMW	Zambian Kwacha\n'


def 					__lowerCamelCase			(      SCREAMING_SNAKE_CASE_     :	str = "USD"  ,  SCREAMING_SNAKE_CASE_     :	str = "INR"  ,  SCREAMING_SNAKE_CASE_     :	float = 1.0  ,  SCREAMING_SNAKE_CASE_     :	str = ""    )							->   str:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_      :			Optional[int]     =       locals()
      # from is a reserved keyword
      SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       params.pop("from_"    )
      SCREAMING_SNAKE_CASE_      :			Dict     =       requests.get(SCREAMING_SNAKE_CASE_  ,  params=SCREAMING_SNAKE_CASE_    ).json()
      return str(res["amount"]    ) if res["error"] == 0 else res["error_message"]


if __name__ == "__main__":
      snake_case_       =       os.getenv('CI', '')
      snake_case_       =       os.getenv('AMDOREN_API_KEY', '')

      if not API_KEY and not TESTING:
            raise KeyError(
                'API key must be provided in the \'AMDOREN_API_KEY\' environment variable.'
            )

      print(
          convert_currency(
              input('Enter from currency: ').strip(),
              input('Enter to currency: ').strip(),
              float(input('Enter the amount: ').strip()),
              API_KEY,
          )
      )




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


snake_case_       =       logging.get_logger(__name__)  # pylint: disable=invalid-name
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase      ):
    _A			    =							42
    _A			    =							None






def 					__lowerCamelCase			(      SCREAMING_SNAKE_CASE_     :	Any  ,  SCREAMING_SNAKE_CASE_     :	int=0.999  ,  SCREAMING_SNAKE_CASE_     :	Optional[Any]="cosine"  ,  )							->   Optional[int]:
      """simple docstring"""

      if alpha_transform_type == "cosine":

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

      elif alpha_transform_type == "exp":

            def alpha_bar_fn(SCREAMING_SNAKE_CASE_     :	Tuple    ):
                  return math.exp(t * -12.0    )

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

      SCREAMING_SNAKE_CASE_      :			List[str]     =       []
      for i in range(SCREAMING_SNAKE_CASE_    ):
            SCREAMING_SNAKE_CASE_      :			List[Any]     =       i / num_diffusion_timesteps
            SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       (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 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase,_UpperCAmelCase      ):
    _A			    =							[e.name for e in KarrasDiffusionSchedulers]
    _A			    =							1




    @register_to_config
    def __init__(					self				,     lowercase__ = 1000				,     lowercase__ = 0.0001				,     lowercase__ = 0.02				,     lowercase__ = "linear"				,     lowercase__ = None				,     lowercase__ = "epsilon"				,     lowercase__ = "linspace"				,     lowercase__ = 0				,     ):






          """simple docstring"""






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

          SCREAMING_SNAKE_CASE_      :			Any     =       1.0 - self.betas
          SCREAMING_SNAKE_CASE_      :			Tuple     =       torch.cumprod(self.alphas				,     dim=0			)

          SCREAMING_SNAKE_CASE_      :			Dict     =       np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
          SCREAMING_SNAKE_CASE_      :			List[str]     =       np.concatenate([sigmas[::-1], [0.0]]			).astype(np.floataa			)
          SCREAMING_SNAKE_CASE_      :			List[str]     =       torch.from_numpy(lowercase__			)

          # setable values
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       None
          SCREAMING_SNAKE_CASE_      :			str     =       np.linspace(0				,     num_train_timesteps - 1				,     lowercase__				,     dtype=lowercase__			)[::-1].copy()
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       torch.from_numpy(lowercase__			)
          SCREAMING_SNAKE_CASE_      :			int     =       False




    @property
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






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

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




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__			):






          """simple docstring"""






          if isinstance(lowercase__				,     torch.Tensor			):
                SCREAMING_SNAKE_CASE_      :			Any     =       timestep.to(self.timesteps.device			)
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       (self.timesteps == timestep).nonzero().item()
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.sigmas[step_index]
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       sample / ((sigma**2 + 1) ** 0.5)
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       True
          return sample




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__ = None			):






          """simple docstring"""






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

          SCREAMING_SNAKE_CASE_      :			int     =       np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
          SCREAMING_SNAKE_CASE_      :			Any     =       np.interp(lowercase__				,     np.arange(0				,     len(lowercase__			)			)				,     lowercase__			)
          SCREAMING_SNAKE_CASE_      :			List[str]     =       np.concatenate([sigmas, [0.0]]			).astype(np.floataa			)
          SCREAMING_SNAKE_CASE_      :			Any     =       torch.from_numpy(lowercase__			).to(device=lowercase__			)
          if str(lowercase__			).startswith("mps"			):
                # mps does not support float64
                SCREAMING_SNAKE_CASE_      :			List[Any]     =       torch.from_numpy(lowercase__			).to(lowercase__				,     dtype=torch.floataa			)
          else:
                SCREAMING_SNAKE_CASE_      :			Tuple     =       torch.from_numpy(lowercase__			).to(device=lowercase__			)




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__ = None				,     lowercase__ = True				,     ):






          """simple docstring"""






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

          SCREAMING_SNAKE_CASE_      :			Tuple     =       (self.timesteps == timestep).nonzero().item()
          SCREAMING_SNAKE_CASE_      :			str     =       self.sigmas[step_index]

          # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
          if self.config.prediction_type == "epsilon":
                SCREAMING_SNAKE_CASE_      :			Any     =       sample - sigma * model_output
          elif self.config.prediction_type == "v_prediction":
                # * c_out + input * c_skip
                SCREAMING_SNAKE_CASE_      :			Any     =       model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
          elif self.config.prediction_type == "sample":
                raise NotImplementedError("prediction_type not implemented yet: sample"			)
          else:
                raise ValueError(
                    F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"			)

          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.sigmas[step_index]
          SCREAMING_SNAKE_CASE_      :			Any     =       self.sigmas[step_index + 1]
          SCREAMING_SNAKE_CASE_      :			Any     =       (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       (sigma_to**2 - sigma_up**2) ** 0.5

          # 2. Convert to an ODE derivative
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       (sample - pred_original_sample) / sigma

          SCREAMING_SNAKE_CASE_      :			List[Any]     =       sigma_down - sigma

          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       sample + derivative * dt

          SCREAMING_SNAKE_CASE_      :			Dict     =       model_output.device
          SCREAMING_SNAKE_CASE_      :			int     =       randn_tensor(model_output.shape				,     dtype=model_output.dtype				,     device=lowercase__				,     generator=lowercase__			)

          SCREAMING_SNAKE_CASE_      :			List[Any]     =       prev_sample + noise * sigma_up

          if not return_dict:
                return (prev_sample,)

          return EulerAncestralDiscreteSchedulerOutput(
              prev_sample=lowercase__				,     pred_original_sample=lowercase__			)




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			str     =       self.sigmas.to(device=original_samples.device				,     dtype=original_samples.dtype			)
          if original_samples.device.type == "mps" and torch.is_floating_point(lowercase__			):
                # mps does not support float64
                SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.timesteps.to(original_samples.device				,     dtype=torch.floataa			)
                SCREAMING_SNAKE_CASE_      :			List[Any]     =       timesteps.to(original_samples.device				,     dtype=torch.floataa			)
          else:
                SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.timesteps.to(original_samples.device			)
                SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       timesteps.to(original_samples.device			)

          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       [(schedule_timesteps == t).nonzero().item() for t in timesteps]

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

          SCREAMING_SNAKE_CASE_      :			Dict     =       original_samples + noise * sigma
          return noisy_samples







    def __len__(					self			):






          """simple docstring"""






          return self.config.num_train_timesteps

