

"""simple docstring"""






import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


_lowerCAmelCase						=		datasets.utils.logging.get_logger(__name__)

_lowerCAmelCase						=		["""names""", """prefix"""]
_lowerCAmelCase						=		["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
_lowerCAmelCase						=		["""encoding_errors""", """on_bad_lines"""]
_lowerCAmelCase						=		["""date_format"""]







@dataclass
class 	__UpperCamelCase    (    datasets.BuilderConfig						):
  _UpperCAmelCase          =		","
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		"infer"
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		"."
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		'"'
  _UpperCAmelCase          =		0
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		0
  _UpperCAmelCase          =		True
  _UpperCAmelCase          =		False
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		1_00_00
  _UpperCAmelCase          =		None
  _UpperCAmelCase          =		"strict"
  _UpperCAmelCase          =		"error"
  _UpperCAmelCase          =		None

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      if self.delimiter is not None:
          _lowerCAmelCase       :   str  =    self.delimiter
      if self.column_names is not None:
          _lowerCAmelCase       :   Dict  =    self.column_names







  @property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    {
          'sep': self.sep,
          'header': self.header,
          'names': self.names,
          'index_col': self.index_col,
          'usecols': self.usecols,
          'prefix': self.prefix,
          'mangle_dupe_cols': self.mangle_dupe_cols,
          'engine': self.engine,
          'converters': self.converters,
          'true_values': self.true_values,
          'false_values': self.false_values,
          'skipinitialspace': self.skipinitialspace,
          'skiprows': self.skiprows,
          'nrows': self.nrows,
          'na_values': self.na_values,
          'keep_default_na': self.keep_default_na,
          'na_filter': self.na_filter,
          'verbose': self.verbose,
          'skip_blank_lines': self.skip_blank_lines,
          'thousands': self.thousands,
          'decimal': self.decimal,
          'lineterminator': self.lineterminator,
          'quotechar': self.quotechar,
          'quoting': self.quoting,
          'escapechar': self.escapechar,
          'comment': self.comment,
          'encoding': self.encoding,
          'dialect': self.dialect,
          'error_bad_lines': self.error_bad_lines,
          'warn_bad_lines': self.warn_bad_lines,
          'skipfooter': self.skipfooter,
          'doublequote': self.doublequote,
          'memory_map': self.memory_map,
          'float_precision': self.float_precision,
          'chunksize': self.chunksize,
          'encoding_errors': self.encoding_errors,
          'on_bad_lines': self.on_bad_lines,
          'date_format': self.date_format,
      }

      # some kwargs must not be passed if they don't have a default value
      # some others are deprecated and we can also not pass them if they are the default value
      for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
          if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()    ,_A      ):
              del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
      if not (datasets.config.PANDAS_VERSION.major >= 2):
          for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
              del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
      if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
          for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
              del pd_read_csv_kwargs[pd_read_csv_parameter]

      return pd_read_csv_kwargs







class 	__UpperCamelCase    (    datasets.ArrowBasedBuilder						):
  _UpperCAmelCase          =		CsvConfig

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return datasets.DatasetInfo(features=self.config.features      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      if not self.config.data_files:
          raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""      )
      _lowerCAmelCase       :   Optional[Any]  =    dl_manager.download_and_extract(self.config.data_files      )
      if isinstance(_A    ,(str, list, tuple)      ):
          _lowerCAmelCase       :   int  =    data_files
          if isinstance(_A    ,_A      ):
              _lowerCAmelCase       :   Optional[int]  =    [files]
          _lowerCAmelCase       :   Dict  =    [dl_manager.iter_files(_A      ) for file in files]
          return [datasets.SplitGenerator(name=datasets.Split.TRAIN    ,gen_kwargs={'files': files}      )]
      _lowerCAmelCase       :   Optional[Any]  =    []
      for split_name, files in data_files.items():
          if isinstance(_A    ,_A      ):
              _lowerCAmelCase       :   List[Any]  =    [files]
          _lowerCAmelCase       :   Dict  =    [dl_manager.iter_files(_A      ) for file in files]
          splits.append(datasets.SplitGenerator(name=_A    ,gen_kwargs={'files': files}      )      )
      return splits

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      if self.config.features is not None:
          _lowerCAmelCase       :   Any  =    self.config.features.arrow_schema
          if all(not require_storage_cast(_A      ) for feature in self.config.features.values()      ):
              # cheaper cast
              _lowerCAmelCase       :   str  =    pa.Table.from_arrays([pa_table[field.name] for field in schema]    ,schema=_A      )
          else:
              # more expensive cast; allows str <-> int/float or str to Audio for example
              _lowerCAmelCase       :   List[str]  =    table_cast(_A    ,_A      )
      return pa_table







  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    self.config.features.arrow_schema if self.config.features else None
      # dtype allows reading an int column as str
      _lowerCAmelCase       :   Dict  =    (
          {
              name: dtype.to_pandas_dtype() if not require_storage_cast(_A      ) else object
              for name, dtype, feature in zip(schema.names    ,schema.types    ,self.config.features.values()      )
          }
          if schema is not None
          else None
      )
      for file_idx, file in enumerate(itertools.chain.from_iterable(_A      )      ):
          _lowerCAmelCase       :   Any  =    pd.read_csv(_A    ,iterator=_A    ,dtype=_A    ,**self.config.pd_read_csv_kwargs      )
          try:
              for batch_idx, df in enumerate(_A      ):
                  _lowerCAmelCase       :   Union[str, Any]  =    pa.Table.from_pandas(_A      )
                  # Uncomment for debugging (will print the Arrow table size and elements)
                  # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                  # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                  yield (file_idx, batch_idx), self._cast_table(_A      )
          except ValueError as e:
              logger.error(F"""Failed to read file '{file}' with error {type(_A      )}: {e}"""      )
              raise








"""simple docstring"""






from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel







class 	__UpperCamelCase    (    a__						):
  _UpperCAmelCase          =		["vqvae"]

  def __init__(		self    ,_A    ,_A    ,_A    ,_A    ,):
      '''simple docstring'''

      super().__init__()
      self.register_modules(unet=_A    ,scheduler=_A    ,mel=_A    ,vqvae=_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return 50 if isinstance(self.scheduler    ,_A      ) else 1000

  @torch.no_grad()
  def __call__(		self    ,_A = 1    ,_A = None    ,_A = None    ,_A = 0    ,_A = 0    ,_A = None    ,_A = None    ,_A = 0    ,_A = 0    ,_A = None    ,_A = 0    ,_A = None    ,_A = None    ,_A=True    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    steps or self.get_default_steps()
      self.scheduler.set_timesteps(_A      )
      _lowerCAmelCase       :   Optional[Any]  =    step_generator or generator
      # For backwards compatibility
      if type(self.unet.config.sample_size      ) == int:
          _lowerCAmelCase       :   Tuple  =    (self.unet.config.sample_size, self.unet.config.sample_size)
      if noise is None:
          _lowerCAmelCase       :   Optional[Any]  =    randn_tensor(
              (
                  batch_size,
                  self.unet.config.in_channels,
                  self.unet.config.sample_size[0],
                  self.unet.config.sample_size[1],
              )    ,generator=_A    ,device=self.device    ,)
      _lowerCAmelCase       :   Dict  =    noise
      _lowerCAmelCase       :   Optional[Any]  =    None

      if audio_file is not None or raw_audio is not None:
          self.mel.load_audio(_A    ,_A      )
          _lowerCAmelCase       :   Union[str, Any]  =    self.mel.audio_slice_to_image(_A      )
          _lowerCAmelCase       :   int  =    np.frombuffer(input_image.tobytes()    ,dtype='uint8'      ).reshape(
              (input_image.height, input_image.width)      )
          _lowerCAmelCase       :   int  =    (input_image / 255) * 2 - 1
          _lowerCAmelCase       :   str  =    torch.tensor(input_image[np.newaxis, :, :]    ,dtype=torch.float      ).to(self.device      )

          if self.vqvae is not None:
              _lowerCAmelCase       :   List[Any]  =    self.vqvae.encode(torch.unsqueeze(_A    ,0      )      ).latent_dist.sample(
                  generator=_A      )[0]
              _lowerCAmelCase       :   Tuple  =    self.vqvae.config.scaling_factor * input_images

          if start_step > 0:
              _lowerCAmelCase       :   List[Any]  =    self.scheduler.add_noise(_A    ,_A    ,self.scheduler.timesteps[start_step - 1]      )

          _lowerCAmelCase       :   Optional[Any]  =    (
              self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
          )
          _lowerCAmelCase       :   Optional[Any]  =    int(mask_start_secs * pixels_per_second      )
          _lowerCAmelCase       :   Optional[int]  =    int(mask_end_secs * pixels_per_second      )
          _lowerCAmelCase       :   int  =    self.scheduler.add_noise(_A    ,_A    ,torch.tensor(self.scheduler.timesteps[start_step:]      )      )

      for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]      )      ):
          if isinstance(self.unet    ,_A      ):
              _lowerCAmelCase       :   str  =    self.unet(_A    ,_A    ,_A      )['sample']
          else:
              _lowerCAmelCase       :   Any  =    self.unet(_A    ,_A      )['sample']

          if isinstance(self.scheduler    ,_A      ):
              _lowerCAmelCase       :   Union[str, Any]  =    self.scheduler.step(
                  model_output=_A    ,timestep=_A    ,sample=_A    ,eta=_A    ,generator=_A    ,)['prev_sample']
          else:
              _lowerCAmelCase       :   Any  =    self.scheduler.step(
                  model_output=_A    ,timestep=_A    ,sample=_A    ,generator=_A    ,)['prev_sample']

          if mask is not None:
              if mask_start > 0:
                  _lowerCAmelCase       :   Any  =    mask[:, step, :, :mask_start]
              if mask_end > 0:
                  _lowerCAmelCase       :   Optional[Any]  =    mask[:, step, :, -mask_end:]

      if self.vqvae is not None:
          # 0.18215 was scaling factor used in training to ensure unit variance
          _lowerCAmelCase       :   Union[str, Any]  =    1 / self.vqvae.config.scaling_factor * images
          _lowerCAmelCase       :   Any  =    self.vqvae.decode(_A      )['sample']

      _lowerCAmelCase       :   Any  =    (images / 2 + 0.5).clamp(0    ,1      )
      _lowerCAmelCase       :   Tuple  =    images.cpu().permute(0    ,2    ,3    ,1      ).numpy()
      _lowerCAmelCase       :   Any  =    (images * 255).round().astype('uint8'      )
      _lowerCAmelCase       :   Any  =    list(
          (Image.fromarray(_[:, :, 0]      ) for _ in images)
          if images.shape[3] == 1
          else (Image.fromarray(_A    ,mode='RGB'      ).convert('L'      ) for _ in images)      )

      _lowerCAmelCase       :   Dict  =    [self.mel.image_to_audio(_A      ) for _ in images]
      if not return_dict:
          return images, (self.mel.get_sample_rate(), audios)

      return BaseOutput(**AudioPipelineOutput(np.array(_A      )[:, np.newaxis, :]      )    ,**ImagePipelineOutput(_A      )      )

  @torch.no_grad()
  def __lowerCamelCase		(		self    ,_A    ,_A = 50      ):
      '''simple docstring'''

      assert isinstance(self.scheduler    ,_A      )
      self.scheduler.set_timesteps(_A      )
      _lowerCAmelCase       :   Dict  =    np.array(
          [np.frombuffer(image.tobytes()    ,dtype='uint8'      ).reshape((1, image.height, image.width)      ) for image in images]      )
      _lowerCAmelCase       :   Dict  =    (sample / 255) * 2 - 1
      _lowerCAmelCase       :   List[str]  =    torch.Tensor(_A      ).to(self.device      )

      for t in self.progress_bar(torch.flip(self.scheduler.timesteps    ,(0,)      )      ):
          _lowerCAmelCase       :   Tuple  =    t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
          _lowerCAmelCase       :   Optional[int]  =    self.scheduler.alphas_cumprod[t]
          _lowerCAmelCase       :   Dict  =    (
              self.scheduler.alphas_cumprod[prev_timestep]
              if prev_timestep >= 0
              else self.scheduler.final_alpha_cumprod
          )
          _lowerCAmelCase       :   Union[str, Any]  =    1 - alpha_prod_t
          _lowerCAmelCase       :   Union[str, Any]  =    self.unet(_A    ,_A      )['sample']
          _lowerCAmelCase       :   Optional[int]  =    (1 - alpha_prod_t_prev) ** 0.5 * model_output
          _lowerCAmelCase       :   Any  =    (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
          _lowerCAmelCase       :   Dict  =    sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

      return sample







  @staticmethod
  def __lowerCamelCase		(		_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    acos(torch.dot(torch.flatten(_A      )    ,torch.flatten(_A      )      ) / torch.norm(_A      ) / torch.norm(_A      )      )
      return sin((1 - alpha) * theta      ) * xa / sin(_A      ) + sin(alpha * theta      ) * xa / sin(_A      )





