






'''simple docstring'''




import math
from typing import Any, Callable, List, Optional, Tuple, Union

import numpy as np
import torch

from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor


if is_onnx_available():
		from ..onnx_utils import OnnxRuntimeModel

from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder


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

lowerCAmelCase__          =						256







class       __lowercase					(__lowerCamelCase    ):
	_lowerCamelCase              =  ['''melgan''']

	def __init__(      self   :						int  ,					UpperCAmelCase_   :						SpectrogramNotesEncoder  ,					UpperCAmelCase_   :						SpectrogramContEncoder  ,					UpperCAmelCase_   :						TaFilmDecoder  ,					UpperCAmelCase_   :						DDPMScheduler  ,					UpperCAmelCase_   :						OnnxRuntimeModel if is_onnx_available() else Any  ,					):
			super().__init__()

			# From MELGAN
			UpperCamelCase__				:					Optional[int]					=					math.log(1e-5)  # Matches MelGAN training.
			UpperCamelCase__				:					Tuple					=					4.0  # Largest value for most examples
			UpperCamelCase__				:					str					=					128

			self.register_modules(
			    notes_encoder=UpperCAmelCase_  ,					continuous_encoder=UpperCAmelCase_  ,					decoder=UpperCAmelCase_  ,					scheduler=UpperCAmelCase_  ,					melgan=UpperCAmelCase_  ,					)

	def      __UpperCamelCase							(      self   :						Dict  ,					UpperCAmelCase_   :						Any  ,					UpperCAmelCase_   :						str=(-1.0, 1.0)  ,					UpperCAmelCase_   :						Union[str, Any]=False):
			UpperCamelCase__,	UpperCamelCase__				:					Dict					=					output_range
			if clip:
					UpperCamelCase__				:					Any					=					torch.clip(UpperCAmelCase_  ,					self.min_value  ,					self.max_value)
			# Scale to [0, 1].
			UpperCamelCase__				:					Dict					=					(features - self.min_value) / (self.max_value - self.min_value)
			# Scale to [min_out, max_out].
			return zero_one * (max_out - min_out) + min_out

	def      __UpperCamelCase							(      self   :						Union[str, Any]  ,					UpperCAmelCase_   :						Dict  ,					UpperCAmelCase_   :						List[Any]=(-1.0, 1.0)  ,					UpperCAmelCase_   :						Dict=False):
			UpperCamelCase__,	UpperCamelCase__				:					Any					=					input_range
			UpperCamelCase__				:					Optional[Any]					=					torch.clip(UpperCAmelCase_  ,					UpperCAmelCase_  ,					UpperCAmelCase_) if clip else outputs
			# Scale to [0, 1].
			UpperCamelCase__				:					Any					=					(outputs - min_out) / (max_out - min_out)
			# Scale to [self.min_value, self.max_value].
			return zero_one * (self.max_value - self.min_value) + self.min_value

	def      __UpperCamelCase							(      self   :						Optional[int]  ,					UpperCAmelCase_   :						List[str]  ,					UpperCAmelCase_   :						str  ,					UpperCAmelCase_   :						Optional[int]):
			UpperCamelCase__				:					Tuple					=					input_tokens > 0
			UpperCamelCase__,	UpperCamelCase__				:					Dict					=					self.notes_encoder(
			    encoder_input_tokens=UpperCAmelCase_  ,					encoder_inputs_mask=UpperCAmelCase_)

			UpperCamelCase__,	UpperCamelCase__				:					Optional[Any]					=					self.continuous_encoder(
			    encoder_inputs=UpperCAmelCase_  ,					encoder_inputs_mask=UpperCAmelCase_)

			return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]

	def      __UpperCamelCase							(      self   :						List[str]  ,					UpperCAmelCase_   :						Tuple  ,					UpperCAmelCase_   :						int  ,					UpperCAmelCase_   :						int):
			UpperCamelCase__				:					List[str]					=					noise_time
			if not torch.is_tensor(UpperCAmelCase_):
					UpperCamelCase__				:					str					=					torch.tensor([timesteps]  ,					dtype=torch.long  ,					device=input_tokens.device)
			elif torch.is_tensor(UpperCAmelCase_) and len(timesteps.shape) == 0:
					UpperCamelCase__				:					Dict					=					timesteps[None].to(input_tokens.device)

			# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
			UpperCamelCase__				:					Optional[Any]					=					timesteps * torch.ones(input_tokens.shape[0]  ,					dtype=timesteps.dtype  ,					device=timesteps.device)

			UpperCamelCase__				:					Any					=					self.decoder(
			    encodings_and_masks=UpperCAmelCase_  ,					decoder_input_tokens=UpperCAmelCase_  ,					decoder_noise_time=UpperCAmelCase_)
			return logits





	@torch.no_grad()
	def __call__(      self   :						List[Any]  ,					UpperCAmelCase_   :						List[List[int]]  ,					UpperCAmelCase_   :						Optional[torch.Generator] = None  ,					UpperCAmelCase_   :						int = 100  ,					UpperCAmelCase_   :						bool = True  ,					UpperCAmelCase_   :						str = "numpy"  ,					UpperCAmelCase_   :						Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,					UpperCAmelCase_   :						int = 1  ,					):
			if (callback_steps is None) or (
			    callback_steps is not None and (not isinstance(UpperCAmelCase_  ,					UpperCAmelCase_) or callback_steps <= 0)
			):
					raise ValueError(
					    F'`callback_steps` has to be a positive integer but is {callback_steps} of type'
					    F' {type(UpperCAmelCase_)}.')

			UpperCamelCase__				:					Dict					=					np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]  ,					dtype=np.floataa)
			UpperCamelCase__				:					List[str]					=					np.zeros([1, 0, self.n_dims]  ,					np.floataa)
			UpperCamelCase__				:					List[str]					=					torch.ones((1, TARGET_FEATURE_LENGTH)  ,					dtype=UpperCAmelCase_  ,					device=self.device)

			for i, encoder_input_tokens in enumerate(UpperCAmelCase_):
					if i == 0:
							UpperCamelCase__				:					List[str]					=					torch.from_numpy(pred_mel[:1].copy()).to(
							    device=self.device  ,					dtype=self.decoder.dtype)
							# The first chunk has no previous context.
							UpperCamelCase__				:					Any					=					torch.zeros((1, TARGET_FEATURE_LENGTH)  ,					dtype=UpperCAmelCase_  ,					device=self.device)
					else:
							# The full song pipeline does not feed in a context feature, so the mask
							# will be all 0s after the feature converter. Because we know we're
							# feeding in a full context chunk from the previous prediction, set it
							# to all 1s.
							UpperCamelCase__				:					Union[str, Any]					=					ones

					UpperCamelCase__				:					Tuple					=					self.scale_features(
					    UpperCAmelCase_  ,					output_range=[-1.0, 1.0]  ,					clip=UpperCAmelCase_)

					UpperCamelCase__				:					Tuple					=					self.encode(
					    input_tokens=torch.IntTensor([encoder_input_tokens]).to(device=self.device)  ,					continuous_inputs=UpperCAmelCase_  ,					continuous_mask=UpperCAmelCase_  ,					)

					# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
					UpperCamelCase__				:					List[Any]					=					randn_tensor(
					    shape=encoder_continuous_inputs.shape  ,					generator=UpperCAmelCase_  ,					device=self.device  ,					dtype=self.decoder.dtype  ,					)

					# set step values
					self.scheduler.set_timesteps(UpperCAmelCase_)

					# Denoising diffusion loop
					for j, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
							UpperCamelCase__				:					Any					=					self.decode(
							    encodings_and_masks=UpperCAmelCase_  ,					input_tokens=UpperCAmelCase_  ,					noise_time=t / self.scheduler.config.num_train_timesteps  ,					)

							# Compute previous output: x_t -> x_t-1
							UpperCamelCase__				:					Optional[int]					=					self.scheduler.step(UpperCAmelCase_  ,					UpperCAmelCase_  ,					UpperCAmelCase_  ,					generator=UpperCAmelCase_).prev_sample

					UpperCamelCase__				:					List[str]					=					self.scale_to_features(UpperCAmelCase_  ,					input_range=[-1.0, 1.0])
					UpperCamelCase__				:					List[str]					=					mel[:1]
					UpperCamelCase__				:					int					=					mel.cpu().float().numpy()

					UpperCamelCase__				:					str					=					np.concatenate([full_pred_mel, pred_mel[:1]]  ,					axis=1)

					# call the callback, if provided
					if callback is not None and i % callback_steps == 0:
							callback(UpperCAmelCase_  ,					UpperCAmelCase_)

					logger.info('Generated segment'  ,					UpperCAmelCase_)

			if output_type == "numpy" and not is_onnx_available():
					raise ValueError(
					    'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.')
			elif output_type == "numpy" and self.melgan is None:
					raise ValueError(
					    'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.')

			if output_type == "numpy":
					UpperCamelCase__				:					Optional[Any]					=					self.melgan(input_features=full_pred_mel.astype(np.floataa))
			else:
					UpperCamelCase__				:					Optional[int]					=					full_pred_mel

			if not return_dict:
					return (output,)

			return AudioPipelineOutput(audios=UpperCAmelCase_)












'''simple docstring'''




import requests
from bsa import BeautifulSoup







def       __UpperCAmelCase						(  lowerCamelCase_ = "AAPL")							->     str:
		UpperCamelCase__				:					str					=					f'https://in.finance.yahoo.com/quote/{symbol}?s={symbol}'
		UpperCamelCase__				:					Optional[Any]					=					BeautifulSoup(requests.get(lowerCamelCase_).text     ,      'html.parser')
		UpperCamelCase__				:					Union[str, Any]					=					'My(6px) Pos(r) smartphone_Mt(6px)'
		return soup.find('div'     ,      class_=class_).find('span').text


if __name__ == "__main__":
		for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
				print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')




