o
    7wiF                     @   s   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZ ddlmZ ddlmZ eeZG d	d
 d
eZG dd deZdddZdd Zdd ZdS )ziDataset examples for loading individual data points

Authors
  * Aku Rouhe 2020
  * Samuele Cornell 2020
    N)
MethodType)Dataset)load_data_csvload_data_json)DataPipeline)batch_shuffle)
get_loggerc                   @   s   e Zd ZdZg g fddZdd Zdd Zdd	d
Zdd Ze	j
dd Zi i i dddfddZi i i dddfddZdd Zdd Zei g g fddZei g g fddZei g g fddZdS )DynamicItemDataseta#  Dataset that reads, wrangles, and produces dicts.

    Each data point dict provides some items (by key), for example, a path to a
    wavefile with the key "wav_file". When a data point is fetched from this
    Dataset, more items are produced dynamically, based on pre-existing items
    and other dynamic created items. For example, a dynamic item could take the
    wavfile path and load the audio from the disk.

    The dynamic items can depend on other dynamic items: a suitable evaluation
    order is used automatically,  as long as there are no circular dependencies.

    A specified list of keys is collected in the output dict. These can be items
    in the original data or dynamic items. If some dynamic items are not
    requested, nor depended on by other requested items, they won't be computed.
    So for example if a user simply wants to iterate over the text, the
    time-consuming audio loading can be skipped.

    About the format:
    Takes a dict of dicts as the collection of data points to read/wrangle.
    The top level keys are data point IDs.
    Each data point (example) dict should have the same keys, corresponding to
    different items in that data point.

    Altogether the data collection could look like this:

    >>> data = {
    ...  "spk1utt1": {
    ...      "wav_file": "/path/to/spk1utt1.wav",
    ...      "text": "hello world",
    ...      "speaker": "spk1",
    ...      },
    ...  "spk1utt2": {
    ...      "wav_file": "/path/to/spk1utt2.wav",
    ...      "text": "how are you world",
    ...      "speaker": "spk1",
    ...      }
    ... }

    NOTE
    ----
        The top-level key, the data point id, is implicitly added as an item
        in the data point, with the key "id"

    Each dynamic item is configured by three things: a key, a func, and a list
    of argkeys. The key should be unique among all the items (dynamic or not) in
    each data point. The func is any callable, and it returns the dynamic item's
    value. The callable is called with the values of other items as specified
    by the argkeys list (as positional args, passed in the order specified by
    argkeys).

    The dynamic_items configuration could look like this:

    >>> import torch
    >>> dynamic_items = [
    ...     {"func": lambda l: torch.Tensor(l),
    ...     "takes": ["wav_loaded"],
    ...     "provides": "wav"},
    ...     {"func": lambda path: [ord(c)/100 for c in path],  # Fake "loading"
    ...     "takes": ["wav_file"],
    ...     "provides": "wav_loaded"},
    ...     {"func": lambda t: t.split(),
    ...     "takes": ["text"],
    ...     "provides": "words"}]

    With these, different views of the data can be loaded:

    >>> from speechbrain.dataio.dataloader import SaveableDataLoader
    >>> from speechbrain.dataio.batch import PaddedBatch
    >>> dataset = DynamicItemDataset(data, dynamic_items)
    >>> dataloader = SaveableDataLoader(dataset, collate_fn=PaddedBatch,
    ...     batch_size=2)
    >>> # First, create encoding for words:
    >>> dataset.set_output_keys(["words"])
    >>> encoding = {}
    >>> next_id = 1
    >>> for batch in dataloader:
    ...     for sent in batch.words:
    ...         for word in sent:
    ...             if word not in encoding:
    ...                 encoding[word] = next_id
    ...                 next_id += 1
    >>> # Next, add an encoded words_tensor dynamic item:
    >>> dataset.add_dynamic_item(
    ...     func = lambda ws: torch.tensor([encoding[w] for w in ws],
    ...             dtype=torch.long),
    ...     takes = ["words"],
    ...     provides = "words_encoded")
    >>> # Now we can get word and audio tensors:
    >>> dataset.set_output_keys(["id", "wav", "words_encoded"])
    >>> batch = next(iter(dataloader))
    >>> batch.id
    ['spk1utt1', 'spk1utt2']
    >>> batch.wav  # +ELLIPSIS
    PaddedData(data=tensor([[0.4700, 1.1200, ...
    >>> batch.words_encoded
    PaddedData(data=tensor([[1, 2, 0, 0],
            [3, 4, 5, 2]]), lengths=tensor([0.5000, 1.0000]))

    Output keys can also be a map:

    >>> dataset.set_output_keys({"id":"id", "signal": "wav", "words": "words_encoded"})
    >>> batch = next(iter(dataloader))
    >>> batch.words
    PaddedData(data=tensor([[1, 2, 0, 0],
            [3, 4, 5, 2]]), lengths=tensor([0.5000, 1.0000]))


    Arguments
    ---------
    data : dict
        Dictionary containing single data points (e.g. utterances).
    dynamic_items : list, optional
        Configuration for the dynamic items produced when fetching an example.
        List of DynamicItems or dicts with the format::
            func: <callable> # To be called
            takes: <list> # key or list of keys of args this takes
            provides: key # key or list of keys that this provides
    output_keys : dict, list, optional
        List of keys (either directly available in data or dynamic items)
        to include in the output dict when data points are fetched.

        If a dict is given; it is used to map internal keys to output keys.
        From the output_keys dict key:value pairs the key appears outside,
        and value is the internal key.
    c                 C   sb   || _ t| j  | _t| j | jd   }d|v rtd|d t||| _| | d S )Nr   idz/The key 'id' is reserved for the data point id.)	datalistkeysdata_ids
ValueErrorappendr   pipelineset_output_keys)selfr   dynamic_itemsoutput_keysstatic_keys r   W/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/speechbrain/dataio/dataset.py__init__   s   
zDynamicItemDataset.__init__c                 C   s
   t | jS N)lenr   r   r   r   r   __len__   s   
zDynamicItemDataset.__len__c                 C   s(   | j | }| j| }| jd|i|S )Nr
   )r   r   r   compute_outputs)r   indexdata_id
data_pointr   r   r   __getitem__   s   

zDynamicItemDataset.__getitem__Nc                 C   s   | j ||| dS )a2  Makes a new dynamic item available on the dataset.

        Two calling conventions. For DynamicItem objects, just use:
        add_dynamic_item(dynamic_item).
        But otherwise, should use:
        add_dynamic_item(func, takes, provides).

        See `speechbrain.utils.data_pipeline`.

        Arguments
        ---------
        func : callable, DynamicItem
            If a DynamicItem is given, adds that directly. Otherwise a
            DynamicItem is created, and this specifies the callable to use. If
            a generator function is given, then create a GeneratorDynamicItem.
            Otherwise creates a normal DynamicItem.
        takes : list, str
            List of keys. When func is called, each key is resolved to
            either an entry in the data or the output of another dynamic_item.
            The func is then called with these as positional arguments,
            in the same order as specified here.
            A single arg can be given directly.
        provides : str
            Unique key or keys that this provides.
        N)r   add_dynamic_item)r   functakesprovidesr   r   r   r#      s   z#DynamicItemDataset.add_dynamic_itemc                 C   s   | j | dS )a  Use this to change the output keys.

        These are the keys that are actually evaluated when a data point
        is fetched from the dataset.

        Arguments
        ---------
        keys : dict, list
            List of keys (str) to produce in output.

            If a dict is given; it is used to map internal keys to output keys.
            From the output_keys dict key:value pairs the key appears outside,
            and value is the internal key.
        N)r   r   )r   r   r   r   r   r      s   z"DynamicItemDataset.set_output_keysc                 c   s,    | j j}| j | | V  | j | dS )a  Context manager to temporarily set output keys.

        Arguments
        ---------
        keys : list
            A set of output keys to use in the context.

        Example
        -------
        >>> dataset = DynamicItemDataset({"a":{"x":1,"y":2},"b":{"x":3,"y":4}},
        ...     output_keys = ["x"])
        >>> with dataset.output_keys_as(["y"]):
        ...     print(dataset[0])
        {'y': 2}
        >>> print(dataset[0])
        {'x': 1}

        NOTE
        ----
        Not thread-safe. While in this context manager, the output keys
        are affected for any call.

        Yields
        ------
        self
        N)r   output_mappingr   )r   r   saved_outputr   r   r   output_keys_as   s
   z!DynamicItemDataset.output_keys_asFc                 C   s   |  ||||||}t| |S )a8  Get a filtered and/or sorted version of this, shares static data.

        The reason to implement these operations in the same method is that
        computing some dynamic items may be expensive, and this way the
        filtering and sorting steps don't need to compute the dynamic items
        twice.

        Arguments
        ---------
        key_min_value : dict
            Map from key (in data or in dynamic items) to limit, will only keep
            data_point if data_point[key] >= limit
        key_max_value : dict
            Map from key (in data or in dynamic items) to limit, will only keep
            data_point if data_point[key] <= limit
        key_test : dict
            Map from key (in data or in dynamic items) to func, will only keep
            data_point if bool(func(data_point[key])) == True
        sort_key : None, str
            If not None, sort by data_point[sort_key]. Default is ascending
            order.
        reverse : bool
            If True, sort in descending order.
        select_n : None, int
            If not None, only keep (at most) the first n filtered data_points.
            The possible sorting is applied, but only on the first n data
            points found. Meant for debugging.

        Returns
        -------
        FilteredSortedDynamicItemDataset
            Shares the static data, but has its own output keys and
            dynamic items (initially deep copied from this, so they have the
            same dynamic items available)

        NOTE
        ----
        Temporarily changes the output keys!
        )_filtered_sorted_ids FilteredSortedDynamicItemDataset)r   key_min_valuekey_max_valuekey_testsort_keyreverseselect_nfiltered_sorted_idsr   r   r   filtered_sorted   s   0z"DynamicItemDataset.filtered_sortedc                    s   fdd}t  t   B t  B t |du r g n|gB }g }	| |E t| jD ]7\}
}|durBt|	|krB n(| j| }||d< | j|}||ri|durd|		|| |
|f q2|		| q2W d   n1 stw   Y  |durdd t
|	|dD }|S |	}|S )zAReturns a list of data ids, fulfilling the sorting and filtering.c                    st     D ]\}}| | |krq dS    D ]\}}| | |kr!q dS   D ]\}}t|| | r5q( dS dS )zApplies filter.FT)itemsbool)computedkeylimitr$   r-   r,   r.   r   r   combined_filter9  s   z@DynamicItemDataset._filtered_sorted_ids.<locals>.combined_filterNr
   c                 S   s   g | ]}|d  qS )   r   ).0tupr   r   r   
<listcomp>d  s    z;DynamicItemDataset._filtered_sorted_ids.<locals>.<listcomp>)r0   )setr   r)   	enumerater   r   r   r   r   r   sorted)r   r,   r-   r.   r/   r0   r1   r:   	temp_keysfiltered_idsir    r!   r6   r2   r   r9   r   r*   .  s<   





z'DynamicItemDataset._filtered_sorted_idsc                 C   s6   t || }| jd| | }|d| }t| |S )a  Creates a subset of this dataset for an overfitting
        test - repeating sample_count samples to create a repeating
        dataset with a total of epoch_data_count samples

        Arguments
        ---------
        sample_count: int
            the number of samples to select
        total_count: int
            the total data count

        Returns
        -------
        dataset: FilteredSortedDynamicItemDataset
            a dataset with a repeated subset
        N)mathceilr   r+   )r   sample_counttotal_countnum_repetitionsoverfit_samplesr   r   r   overfit_testk  s   
zDynamicItemDataset.overfit_testc                 C   s   t | j|}t| |S )a  Shuffles batches within a dataset. This is particularly
        useful in combination with length sorting - to ensure
        that the length variation within a batch is not very high,
        but the batches themselves remain randomized

        Arguments
        ---------
        batch_size: int
            the batch size

        Returns
        -------
        dataset: FilteredSortedDynamicItemDataset
            a shuffled dataset
        )r   r   r+   )r   
batch_sizer   r   r   r   r     s   
z DynamicItemDataset.batch_shufflec                 C      t ||}| |||S )z<Load a data prep JSON file and create a Dataset based on it.)r   )cls	json_pathreplacementsr   r   r   r   r   r   	from_json     
zDynamicItemDataset.from_jsonc                 C   rM   )z;Load a data prep CSV file and create a Dataset based on it.)r   )rN   csv_pathrP   r   r   r   r   r   r   from_csv  rR   zDynamicItemDataset.from_csvc                    s$    fdd}t |  _|  ||S )z&Loading a prepared huggingface datasetc                    s   dd t   D S )zReturns the keys.c                 S   s   g | ]}|qS r   r   )r<   rD   r   r   r   r>     s    zGDynamicItemDataset.from_arrow_dataset.<locals>.keys.<locals>.<listcomp>)ranger   r   datasetr   r   r     s   z3DynamicItemDataset.from_arrow_dataset.<locals>.keys)r   r   )rN   rW   rP   r   r   r   r   rV   r   from_arrow_dataset  s   z%DynamicItemDataset.from_arrow_datasetNN)__name__
__module____qualname____doc__r   r   r"   r#   r   
contextlibcontextmanagerr)   r3   r*   rK   r   classmethodrQ   rT   rX   r   r   r   r   r	      sD    ~

"
9
=r	   c                   @   s@   e Zd ZdZdd Zei ddfddZei ddfddZdS )	r+   zPossibly filtered, possibly sorted DynamicItemDataset.

    Shares the static data (reference).
    Has its own dynamic_items and output_keys (deepcopy).
    c                 C   s    |j | _ || _t|j| _d S r   )r   r   copydeepcopyr   )r   from_datasetr   r   r   r   r     s   z)FilteredSortedDynamicItemDataset.__init__Nc                 C      t dNz0Cannot create SubsetDynamicItemDataset directly!	TypeError)rN   rO   rP   r   r   r   r   r   rQ        z*FilteredSortedDynamicItemDataset.from_jsonc                 C   rd   re   rf   )rN   rS   rP   r   r   r   r   r   rT     rh   z)FilteredSortedDynamicItemDataset.from_csv)rZ   r[   r\   r]   r   r`   rQ   rT   r   r   r   r   r+     s    r+   c                 C   s   | D ]	}| ||| qdS )z5Helper for adding the same item to multiple datasets.N)r#   )datasetsr$   r%   r&   rW   r   r   r   r#     s   r#   c                 C   s   | D ]}| | qdS )z6Helper for setting the same item to multiple datasets.N)r   )ri   r   rW   r   r   r   r     s   r   c                 C   s   | r|}|}| ||}|S )a  Applies the overfit test to the specified dataset,
    as configured in the hyperparameters file

    Arguments
    ---------

    overfit_test: bool
        when True the overfitting test is performed
    overfit_test_sample_count: int
        number of samples for the overfitting test
    overfit_test_epoch_data_count: int
        number of epochs for the overfitting test

    dataset: DynamicItemDataset
        the dataset

    Returns
    -------
    dataset: DynamicItemDataset
        the dataset, with the overfit test apply
    )rK   )rK   overfit_test_sample_countoverfit_test_epoch_data_countrW   rG   epoch_data_countr   r   r   apply_overfit_test  s
   rm   rY   )r]   r^   ra   rE   typesr   torch.utils.datar   speechbrain.dataio.dataior   r   speechbrain.utils.data_pipeliner   speechbrain.utils.data_utilsr   speechbrain.utils.loggerr   rZ   loggerr	   r+   r#   r   rm   r   r   r   r   <module>   s&        
