





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


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

A_												=     2_5_6

class SCREAMING_SNAKE_CASE_ (					lowercase_   ):





					"""simple docstring"""


					A__				 =    ["melgan"]





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

										# From MELGAN
										lowerCamelCase__       =       math.log(1E-5	)  # Matches MelGAN training.
										lowerCamelCase__       =       4.0  # Largest value for most examples
										lowerCamelCase__       =       128

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





					def 					__magic_name__ ( self	,  _lowerCAmelCase	,  _lowerCAmelCase=(-1.0, 1.0)	,  _lowerCAmelCase=False	):
										lowerCamelCase__    ,		lowerCamelCase__       =       output_range
										if clip:
															lowerCamelCase__       =       torch.clip(_lowerCAmelCase	,  self.min_value	,  self.max_value	)
										# Scale to [0, 1].
										lowerCamelCase__       =       (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 					__magic_name__ ( self	,  _lowerCAmelCase	,  _lowerCAmelCase=(-1.0, 1.0)	,  _lowerCAmelCase=False	):
										lowerCamelCase__    ,		lowerCamelCase__       =       input_range
										lowerCamelCase__       =       torch.clip(_lowerCAmelCase	,  _lowerCAmelCase	,  _lowerCAmelCase	) if clip else outputs
										# Scale to [0, 1].
										lowerCamelCase__       =       (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 					__magic_name__ ( self	,  _lowerCAmelCase	,  _lowerCAmelCase	,  _lowerCAmelCase	):
										lowerCamelCase__       =       input_tokens > 0
										lowerCamelCase__    ,		lowerCamelCase__       =       self.notes_encoder(
										    encoder_input_tokens=_lowerCAmelCase	,  encoder_inputs_mask=_lowerCAmelCase	)

										lowerCamelCase__    ,		lowerCamelCase__       =       self.continuous_encoder(
										    encoder_inputs=_lowerCAmelCase	,  encoder_inputs_mask=_lowerCAmelCase	)

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





					def 					__magic_name__ ( self	,  _lowerCAmelCase	,  _lowerCAmelCase	,  _lowerCAmelCase	):
										lowerCamelCase__       =       noise_time
										if not torch.is_tensor(_lowerCAmelCase	):
															lowerCamelCase__       =       torch.tensor([timesteps]	,  dtype=torch.long	,  device=input_tokens.device	)
										elif torch.is_tensor(_lowerCAmelCase	) and len(timesteps.shape	) == 0:
															lowerCamelCase__       =       timesteps[None].to(input_tokens.device	)

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

										lowerCamelCase__       =       self.decoder(
										    encodings_and_masks=_lowerCAmelCase	,  decoder_input_tokens=_lowerCAmelCase	,  decoder_noise_time=_lowerCAmelCase	)
										return logits






					@torch.no_grad()
					def __call__( self	,  _lowerCAmelCase	,  _lowerCAmelCase = None	,  _lowerCAmelCase = 100	,  _lowerCAmelCase = True	,  _lowerCAmelCase = "numpy"	,  _lowerCAmelCase = None	,  _lowerCAmelCase = 1	,  ):
										if (callback_steps is None) or (
										    callback_steps is not None and (not isinstance(_lowerCAmelCase	,  _lowerCAmelCase	) or callback_steps <= 0)
										):
															raise ValueError(
															    F"`callback_steps` has to be a positive integer but is {callback_steps} of type"
															    F" {type(_lowerCAmelCase	)}."	)

										lowerCamelCase__       =       np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]	,  dtype=np.floataa	)
										lowerCamelCase__       =       np.zeros([1, 0, self.n_dims]	,  np.floataa	)
										lowerCamelCase__       =       torch.ones((1, TARGET_FEATURE_LENGTH)	,  dtype=_lowerCAmelCase	,  device=self.device	)

										for i, encoder_input_tokens in enumerate(_lowerCAmelCase	):
															if i == 0:
																				lowerCamelCase__       =       torch.from_numpy(pred_mel[:1].copy()	).to(
																				    device=self.device	,  dtype=self.decoder.dtype	)
																				# The first chunk has no previous context.
																				lowerCamelCase__       =       torch.zeros((1, TARGET_FEATURE_LENGTH)	,  dtype=_lowerCAmelCase	,  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.
																				lowerCamelCase__       =       ones

															lowerCamelCase__       =       self.scale_features(
															    _lowerCAmelCase	,  output_range=[-1.0, 1.0]	,  clip=_lowerCAmelCase	)

															lowerCamelCase__       =       self.encode(
															    input_tokens=torch.IntTensor([encoder_input_tokens]	).to(device=self.device	)	,  continuous_inputs=_lowerCAmelCase	,  continuous_mask=_lowerCAmelCase	,  )

															# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
															lowerCamelCase__       =       randn_tensor(
															    shape=encoder_continuous_inputs.shape	,  generator=_lowerCAmelCase	,  device=self.device	,  dtype=self.decoder.dtype	,  )

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

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

																				# Compute previous output: x_t -> x_t-1
																				lowerCamelCase__       =       self.scheduler.step(_lowerCAmelCase	,  _lowerCAmelCase	,  _lowerCAmelCase	,  generator=_lowerCAmelCase	).prev_sample

															lowerCamelCase__       =       self.scale_to_features(_lowerCAmelCase	,  input_range=[-1.0, 1.0]	)
															lowerCamelCase__       =       mel[:1]
															lowerCamelCase__       =       mel.cpu().float().numpy()

															lowerCamelCase__       =       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(_lowerCAmelCase	,  _lowerCAmelCase	)

															logger.info("Generated segment"	,  _lowerCAmelCase	)

										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":
															lowerCamelCase__       =       self.melgan(input_features=full_pred_mel.astype(np.floataa	)	)
										else:
															lowerCamelCase__       =       full_pred_mel

										if not return_dict:
															return (output,)

										return AudioPipelineOutput(audios=_lowerCAmelCase	)








import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


A_												=     logging.get_logger(__name__)

A_												=     list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A_												=     tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class SCREAMING_SNAKE_CASE_ :





					"""simple docstring"""


					A__				 =    field(
					    default=lowercase_							,       metadata={"help": "Model type selected in the list: " + ", ".join(lowercase_   )}   )
					A__				 =    field(
					    default=lowercase_							,       metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."}   )
					A__				 =    field(
					    default=1_2_8							,       metadata={
					        "help": (
					            "The maximum total input sequence length after tokenization. Sequences longer "
					            "than this will be truncated, sequences shorter will be padded."
					        )
					    }							,       )
					A__				 =    field(
					    default=1_2_8							,       metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}							,       )
					A__				 =    field(
					    default=6_4							,       metadata={
					        "help": (
					            "The maximum number of tokens for the question. Questions longer than this will "
					            "be truncated to this length."
					        )
					    }							,       )
					A__				 =    field(
					    default=3_0							,       metadata={
					        "help": (
					            "The maximum length of an answer that can be generated. This is needed because the start "
					            "and end predictions are not conditioned on one another."
					        )
					    }							,       )
					A__				 =    field(
					    default=lowercase_							,       metadata={"help": "Overwrite the cached training and evaluation sets"}   )
					A__				 =    field(
					    default=lowercase_							,       metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."}   )
					A__				 =    field(
					    default=0.0							,       metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}   )
					A__				 =    field(
					    default=2_0							,       metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}   )
					A__				 =    field(
					    default=0							,       metadata={
					        "help": (
					            "language id of input for language-specific xlm models (see"
					            " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
					        )
					    }							,       )
					A__				 =    field(default=1							,       metadata={"help": "multiple threads for converting example to features"}   )

class SCREAMING_SNAKE_CASE_ (					lowercase_   ):





					"""simple docstring"""


					A__				 =    "train"
					A__				 =    "dev"

class SCREAMING_SNAKE_CASE_ (					lowercase_   ):





					"""simple docstring"""


					A__				 =    42
					A__				 =    42
					A__				 =    42
					A__				 =    42





					def __init__( self	,  _lowerCAmelCase	,  _lowerCAmelCase	,  _lowerCAmelCase = None	,  _lowerCAmelCase = Split.train	,  _lowerCAmelCase = False	,  _lowerCAmelCase = None	,  _lowerCAmelCase = "pt"	,  ):
										lowerCamelCase__       =       args
										lowerCamelCase__       =       is_language_sensitive
										lowerCamelCase__       =       SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
										if isinstance(_lowerCAmelCase	,  _lowerCAmelCase	):
															try:
																				lowerCamelCase__       =       Split[mode]
															except KeyError:
																				raise KeyError("mode is not a valid split name"	)
										lowerCamelCase__       =       mode
										# Load data features from cache or dataset file
										lowerCamelCase__       =       "v2" if args.version_2_with_negative else "v1"
										lowerCamelCase__       =       os.path.join(
										    cache_dir if cache_dir is not None else args.data_dir	,  F"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"	,  )

										# Make sure only the first process in distributed training processes the dataset,
										# and the others will use the cache.
										lowerCamelCase__       =       cached_features_file + ".lock"
										with FileLock(_lowerCAmelCase	):
															if os.path.exists(_lowerCAmelCase	) and not args.overwrite_cache:
																				lowerCamelCase__       =       time.time()
																				lowerCamelCase__       =       torch.load(_lowerCAmelCase	)

																				# Legacy cache files have only features, while new cache files
																				# will have dataset and examples also.
																				lowerCamelCase__       =       self.old_features["features"]
																				lowerCamelCase__       =       self.old_features.get("dataset"	,  _lowerCAmelCase	)
																				lowerCamelCase__       =       self.old_features.get("examples"	,  _lowerCAmelCase	)
																				logger.info(
																				    F"Loading features from cached file {cached_features_file} [took %.3f s]"	,  time.time() - start	)

																				if self.dataset is None or self.examples is None:
																									logger.warning(
																									    F"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
																									    " future run"	)
															else:
																				if mode == Split.dev:
																									lowerCamelCase__       =       self.processor.get_dev_examples(args.data_dir	)
																				else:
																									lowerCamelCase__       =       self.processor.get_train_examples(args.data_dir	)

																				lowerCamelCase__    ,		lowerCamelCase__       =       squad_convert_examples_to_features(
																				    examples=self.examples	,  tokenizer=_lowerCAmelCase	,  max_seq_length=args.max_seq_length	,  doc_stride=args.doc_stride	,  max_query_length=args.max_query_length	,  is_training=mode == Split.train	,  threads=args.threads	,  return_dataset=_lowerCAmelCase	,  )

																				lowerCamelCase__       =       time.time()
																				torch.save(
																				    {"features": self.features, "dataset": self.dataset, "examples": self.examples}	,  _lowerCAmelCase	,  )
																				# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																				logger.info(
																				    F"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"	)





					def __len__( self	):
										return len(self.features	)






					def __getitem__( self	,  _lowerCAmelCase	):
										# Convert to Tensors and build dataset
										lowerCamelCase__       =       self.features[i]

										lowerCamelCase__       =       torch.tensor(feature.input_ids	,  dtype=torch.long	)
										lowerCamelCase__       =       torch.tensor(feature.attention_mask	,  dtype=torch.long	)
										lowerCamelCase__       =       torch.tensor(feature.token_type_ids	,  dtype=torch.long	)
										lowerCamelCase__       =       torch.tensor(feature.cls_index	,  dtype=torch.long	)
										lowerCamelCase__       =       torch.tensor(feature.p_mask	,  dtype=torch.float	)
										lowerCamelCase__       =       torch.tensor(feature.is_impossible	,  dtype=torch.float	)

										lowerCamelCase__       =       {
										    "input_ids": input_ids,
										    "attention_mask": attention_mask,
										    "token_type_ids": token_type_ids,
										}

										if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
															del inputs["token_type_ids"]

										if self.args.model_type in ["xlnet", "xlm"]:
															inputs.update({"cls_index": cls_index, "p_mask": p_mask}	)
															if self.args.version_2_with_negative:
																				inputs.update({"is_impossible": is_impossible}	)
															if self.is_language_sensitive:
																				inputs.update({"langs": (torch.ones(input_ids.shape	,  dtype=torch.intaa	) * self.args.lang_id)}	)

										if self.mode == Split.train:
															lowerCamelCase__       =       torch.tensor(feature.start_position	,  dtype=torch.long	)
															lowerCamelCase__       =       torch.tensor(feature.end_position	,  dtype=torch.long	)
															inputs.update({"start_positions": start_positions, "end_positions": end_positions}	)

										return inputs

