o
    ziE                     @   s   d dl mZ d dlmZ d dlmZ d dlmZ d dlmZ d dlZd dl	m
Z
 d dlmZ d	d
lmZ d	dlmZ G dd dZdd ZefdefddZG dd dZG dd deZG dd deZG dd de
ZdS )    )Path)Callable)Dict)List)UnionN)SequentialSampler)DistributedSampler   )AudioSignal)utilc                   @   s   e Zd ZdZddddejddfdee dee de	d	ed
ee de
defddZ						ddedededededededefddZdS )AudioLoaderaP  Loads audio endlessly from a list of audio sources
    containing paths to audio files. Audio sources can be
    folders full of audio files (which are found via file
    extension) or by providing a CSV file which contains paths
    to audio files.

    Parameters
    ----------
    sources : List[str], optional
        Sources containing folders, or CSVs with
        paths to audio files, by default None
    weights : List[float], optional
        Weights to sample audio files from each source, by default None
    relative_path : str, optional
        Path audio should be loaded relative to, by default ""
    transform : Callable, optional
        Transform to instantiate alongside audio sample,
        by default None
    ext : List[str]
        List of extensions to find audio within each source by. Can
        also be a file name (e.g. "vocals.wav"). by default
        ``['.wav', '.flac', '.mp3', '.mp4']``.
    shuffle: bool
        Whether to shuffle the files within the dataloader. Defaults to True.
    shuffle_state: int
        State to use to seed the shuffle of the files.
    N Tr   sourcesweights	transformrelative_pathextshuffleshuffle_statec           	      C   sX   t j|||d| _dd t| jD | _|r!t |}|| j || _|| _|| _	d S )N)r   r   c                 S   s*   g | ]\}}t t|D ]}||fqqS  )rangelen).0src_idxsrcitem_idxr   r   L/home/ubuntu/.local/lib/python3.10/site-packages/audiotools/data/datasets.py
<listcomp>:   s    
z(AudioLoader.__init__.<locals>.<listcomp>)
r   read_sourcesaudio_lists	enumerateaudio_indicesrandom_stater   r   r   r   )	selfr   r   r   r   r   r   r   stater   r   r   __init__,   s   


zAudioLoader.__init__   sample_ratedurationloudness_cutoffnum_channelsoffset
source_idxr   
global_idxc
                 C   sZ  |d ur|d urz	| j | | }
W n.   ddi}
Y n%|	d ur3| j|	t| j  \}}| j | | }
ntj|| j | jd\}
}}|
d }t|||}|dkrd|d u r]tj||||d}nt|||d}|dkrl|	 }|
|}|j|k r|t|| }|
 D ]	\}}||j|< q|||t| j| t|d}| jd ur| jj||d|d	< |S )
Npathnone)p)r)   r$   r*   )r,   r)   r'   )signalr-   r   sourcer/   )r2   transform_args)r   r!   r   r   choose_from_list_of_listsr   r
   zerossalient_excerptto_monoresampler)   zero_pad_tointitemsmetadatastrr   r   instantiate)r#   r$   r(   r)   r*   r+   r,   r-   r   r.   
audio_infor/   r2   kvitemr   r   r   __call__G   sX   



zAudioLoader.__call__)r&   r'   NNNN)__name__
__module____qualname____doc__r   AUDIO_EXTENSIONSr   r>   floatr   boolr;   r%   rD   r   r   r   r   r      s^    
 	
r   c                 C   s   t | jt |jkS N)r   parent)xyr   r   r   default_matcher      rP   matcherc                 C   sz   | t dd | D  }t|D ]*\}}| D ]#}|t|kr&|ddi q||| d |d s9||ddi qq| S )Nc                 S      g | ]}t |qS r   r   r   lr   r   r   r          zalign_lists.<locals>.<listcomp>r/   r0   )npargmaxr    r   appendinsert)listsrR   longest_listirN   rV   r   r   r   align_lists   s   r_   c                   @   s   e Zd ZdZddddddddedf
d	eeee ee	ef f d
e
de
dededede
dededededefddZdd Zdd Zeddeeef de
fddZdS ) AudioDataseta#  Loads audio from multiple loaders (with associated transforms)
    for a specified number of samples. Excerpts are drawn randomly
    of the specified duration, above a specified loudness threshold
    and are resampled on the fly to the desired sample rate
    (if it is different from the audio source sample rate).

    This takes either a single AudioLoader object,
    a dictionary of AudioLoader objects, or a dictionary of AudioLoader
    objects. Each AudioLoader is called by the dataset, and the
    result is placed in the output dictionary. A transform can also be
    specified for the entire dataset, rather than for each specific
    loader. This transform can be applied to the output of all the
    loaders if desired.

    AudioLoader objects can be specified as aligned, which means the
    loaders correspond to multitrack audio (e.g. a vocals, bass,
    drums, and other loader for multitrack music mixtures).


    Parameters
    ----------
    loaders : Union[AudioLoader, List[AudioLoader], Dict[str, AudioLoader]]
        AudioLoaders to sample audio from.
    sample_rate : int
        Desired sample rate.
    n_examples : int, optional
        Number of examples (length of dataset), by default 1000
    duration : float, optional
        Duration of audio samples, by default 0.5
    loudness_cutoff : float, optional
        Loudness cutoff threshold for audio samples, by default -40
    num_channels : int, optional
        Number of channels in output audio, by default 1
    transform : Callable, optional
        Transform to instantiate alongside each dataset item, by default None
    aligned : bool, optional
        Whether the loaders should be sampled in an aligned manner (e.g. same
        offset, duration, and matched file name), by default False
    shuffle_loaders : bool, optional
        Whether to shuffle the loaders before sampling from them, by default False
    matcher : Callable
        How to match files from adjacent audio lists (e.g. for a multitrack audio loader),
        by default uses the parent directory of each file.
    without_replacement : bool
        Whether to choose files with or without replacement, by default True.


    Examples
    --------
    >>> from audiotools.data.datasets import AudioLoader
    >>> from audiotools.data.datasets import AudioDataset
    >>> from audiotools import transforms as tfm
    >>> import numpy as np
    >>>
    >>> loaders = [
    >>>     AudioLoader(
    >>>         sources=[f"tests/audio/spk"],
    >>>         transform=tfm.Equalizer(),
    >>>         ext=["wav"],
    >>>     )
    >>>     for i in range(5)
    >>> ]
    >>>
    >>> dataset = AudioDataset(
    >>>     loaders = loaders,
    >>>     sample_rate = 44100,
    >>>     duration = 1.0,
    >>>     transform = tfm.RescaleAudio(),
    >>> )
    >>>
    >>> item = dataset[np.random.randint(len(dataset))]
    >>>
    >>> for i in range(len(loaders)):
    >>>     item[i]["signal"] = loaders[i].transform(
    >>>         item[i]["signal"], **item[i]["transform_args"]
    >>>     )
    >>>     item[i]["signal"].widget(i)
    >>>
    >>> mix = sum([item[i]["signal"] for i in range(len(loaders))])
    >>> mix = dataset.transform(mix, **item["transform_args"])
    >>> mix.widget("mix")

    Below is an example of how one could load MUSDB multitrack data:

    >>> import audiotools as at
    >>> from pathlib import Path
    >>> from audiotools import transforms as tfm
    >>> import numpy as np
    >>> import torch
    >>>
    >>> def build_dataset(
    >>>     sample_rate: int = 44100,
    >>>     duration: float = 5.0,
    >>>     musdb_path: str = "~/.data/musdb/",
    >>> ):
    >>>     musdb_path = Path(musdb_path).expanduser()
    >>>     loaders = {
    >>>         src: at.datasets.AudioLoader(
    >>>             sources=[musdb_path],
    >>>             transform=tfm.Compose(
    >>>                 tfm.VolumeNorm(("uniform", -20, -10)),
    >>>                 tfm.Silence(prob=0.1),
    >>>             ),
    >>>             ext=[f"{src}.wav"],
    >>>         )
    >>>         for src in ["vocals", "bass", "drums", "other"]
    >>>     }
    >>>
    >>>     dataset = at.datasets.AudioDataset(
    >>>         loaders=loaders,
    >>>         sample_rate=sample_rate,
    >>>         duration=duration,
    >>>         num_channels=1,
    >>>         aligned=True,
    >>>         transform=tfm.RescaleAudio(),
    >>>         shuffle_loaders=True,
    >>>     )
    >>>     return dataset, list(loaders.keys())
    >>>
    >>> train_data, sources = build_dataset()
    >>> dataloader = torch.utils.data.DataLoader(
    >>>     train_data,
    >>>     batch_size=16,
    >>>     num_workers=0,
    >>>     collate_fn=train_data.collate,
    >>> )
    >>> batch = next(iter(dataloader))
    >>>
    >>> for k in sources:
    >>>     src = batch[k]
    >>>     src["transformed"] = train_data.loaders[k].transform(
    >>>         src["signal"].clone(), **src["transform_args"]
    >>>     )
    >>>
    >>> mixture = sum(batch[k]["transformed"] for k in sources)
    >>> mixture = train_data.transform(mixture, **batch["transform_args"])
    >>>
    >>> # Say a model takes the mix and gives back (n_batch, n_src, n_time).
    >>> # Construct the targets:
    >>> targets = at.AudioSignal.batch([batch[k]["transformed"] for k in sources], dim=1)

    Similarly, here's example code for loading Slakh data:

    >>> import audiotools as at
    >>> from pathlib import Path
    >>> from audiotools import transforms as tfm
    >>> import numpy as np
    >>> import torch
    >>> import glob
    >>>
    >>> def build_dataset(
    >>>     sample_rate: int = 16000,
    >>>     duration: float = 10.0,
    >>>     slakh_path: str = "~/.data/slakh/",
    >>> ):
    >>>     slakh_path = Path(slakh_path).expanduser()
    >>>
    >>>     # Find the max number of sources in Slakh
    >>>     src_names = [x.name for x in list(slakh_path.glob("**/*.wav"))  if "S" in str(x.name)]
    >>>     n_sources = len(list(set(src_names)))
    >>>
    >>>     loaders = {
    >>>         f"S{i:02d}": at.datasets.AudioLoader(
    >>>             sources=[slakh_path],
    >>>             transform=tfm.Compose(
    >>>                 tfm.VolumeNorm(("uniform", -20, -10)),
    >>>                 tfm.Silence(prob=0.1),
    >>>             ),
    >>>             ext=[f"S{i:02d}.wav"],
    >>>         )
    >>>         for i in range(n_sources)
    >>>     }
    >>>     dataset = at.datasets.AudioDataset(
    >>>         loaders=loaders,
    >>>         sample_rate=sample_rate,
    >>>         duration=duration,
    >>>         num_channels=1,
    >>>         aligned=True,
    >>>         transform=tfm.RescaleAudio(),
    >>>         shuffle_loaders=False,
    >>>     )
    >>>
    >>>     return dataset, list(loaders.keys())
    >>>
    >>> train_data, sources = build_dataset()
    >>> dataloader = torch.utils.data.DataLoader(
    >>>     train_data,
    >>>     batch_size=16,
    >>>     num_workers=0,
    >>>     collate_fn=train_data.collate,
    >>> )
    >>> batch = next(iter(dataloader))
    >>>
    >>> for k in sources:
    >>>     src = batch[k]
    >>>     src["transformed"] = train_data.loaders[k].transform(
    >>>         src["signal"].clone(), **src["transform_args"]
    >>>     )
    >>>
    >>> mixture = sum(batch[k]["transformed"] for k in sources)
    >>> mixture = train_data.transform(mixture, **batch["transform_args"])

    i  g      ?Nr&   r'   FTloadersr(   
n_examplesr)   r,   r*   r+   r   alignedshuffle_loadersrR   without_replacementc                    s   t |trdd t|D }n	t |trd|i}|| _|| _|| _|| _|| _|| _	|| _
|| _|	| _|
| _|| _|	r[t| }tt|d jD ]  fdd|D }t|| qJd S d S )Nc                 S   s   i | ]\}}||qS r   r   )r   r^   rV   r   r   r   
<dictcomp>w      z)AudioDataset.__init__.<locals>.<dictcomp>r   c                    s   g | ]}|j   qS r   )r   rU   r^   r   r   r     rg   z)AudioDataset.__init__.<locals>.<listcomp>)
isinstancelistr    r   ra   r*   r+   lengthr   r(   r)   r,   rc   rd   re   valuesr   r   r   r_   )r#   ra   r(   rb   r)   r,   r*   r+   r   rc   rd   rR   re   loaders_listinput_listsr   rh   r   r%   f  s,   

zAudioDataset.__init__c                    sr  t |}| jd u rd n| j}i  t| j }| jr || || j| j	| j
| j| jr.|nd d}| j|d  }|di | |d < |dd  D ]3}| j| }| jrt |d  d jd }|| |d  d  |d  d d |di | |< qJt| j } fd	d
|D  | d< | jd ur| jj| |d  d d d< t|dkr  |d   S )N)r$   r(   r)   r*   r+   r.   r   r'   r2   r,   r-   r   )r,   r-   r   c                    s   i | ]}| | qS r   r   )r   rA   rC   r   r   rf     rg   z,AudioDataset.__getitem__.<locals>.<dictcomp>idx)r$   r2   r4   r   )r   r"   r,   rj   ra   keysrd   r   r(   r)   r*   r+   re   rc   r=   updater   r?   r   pop)r#   rp   r$   r,   rq   loader_kwargsloaderkeyr   ro   r   __getitem__  sH   





zAudioDataset.__getitem__c                 C   s   | j S rL   )rk   r#   r   r   r   __len__  s   zAudioDataset.__len__list_of_dictsn_splitsc                 C   s   t j| |dS )a  Collates items drawn from this dataset. Uses
        :py:func:`audiotools.core.util.collate`.

        Parameters
        ----------
        list_of_dicts : typing.Union[list, dict]
            Data drawn from each item.
        n_splits : int
            Number of splits to make when creating the batches (split into
            sub-batches). Useful for things like gradient accumulation.

        Returns
        -------
        dict
            Dictionary of batched data.
        )r{   )r   collate)rz   r{   r   r   r   r|     s   zAudioDataset.collaterL   )rE   rF   rG   rH   rP   r   r   r   r   r>   r;   rJ   r   rK   r%   rw   ry   staticmethodrj   dictr|   r   r   r   r   r`      sT     Q	

)7"r`   c                   @   s*   e Zd ZdefddZdd Zdd ZdS )	ConcatDatasetdatasetsc                 C   s
   || _ d S rL   )r   )r#   r   r   r   r   r%     s   
zConcatDataset.__init__c                 C   s   t dd | jD S )Nc                 S   rS   r   rT   )r   dr   r   r   r     rW   z)ConcatDataset.__len__.<locals>.<listcomp>)sumr   rx   r   r   r   ry     rQ   zConcatDataset.__len__c                 C   s&   | j |t| j   }||t| j   S rL   )r   r   )r#   rp   datasetr   r   r   rw     s   zConcatDataset.__getitem__N)rE   rF   rG   rj   r%   ry   rw   r   r   r   r   r     s    r   c                       4   e Zd ZdZddef fddZ fddZ  ZS )	ResumableDistributedSamplerzADistributed sampler that can be resumed from a given start index.N	start_idxc                    s6   t  j|fi | |d ur|| j | _d S d| _d S Nr   )superr%   num_replicasr   r#   r   r   kwargs	__class__r   r   r%     s   "z$ResumableDistributedSampler.__init__c                 #   4    t t  D ]\}}|| jkr|V  qd| _d S r   r    r   __iter__r   r#   r^   rp   r   r   r   r        

z$ResumableDistributedSampler.__iter__rL   rE   rF   rG   rH   r;   r%   r   __classcell__r   r   r   r   r         r   c                       r   )	ResumableSequentialSamplerz@Sequential sampler that can be resumed from a given start index.Nr   c                    s0   t  j|fi | |d ur|| _d S d| _d S r   )r   r%   r   r   r   r   r   r%     s   z#ResumableSequentialSampler.__init__c                 #   r   r   r   r   r   r   r   r     r   z#ResumableSequentialSampler.__iter__rL   r   r   r   r   r   r     r   r   )pathlibr   typingr   r   r   r   numpyrX   torch.utils.datar   torch.utils.data.distributedr   corer
   r   r   rP   r_   r`   r   r   r   r   r   r   r   <module>   s&    {  G