
      i!                     j    d dl mZ d dlmZmZ d dlZd dlZd dlmZ d dlZeeee	f   Z
	  G d d      Zy)    )Path)TextUnionN)Tensorc            	            e Zd ZdZededefd       Zededefd       Z	ede
eef   defd       Zdedefd	Zdd
edef fdZded
edefdZ	 ddedededefdZ xZS )AudiouI  Audio IO with on-the-fly resampling

    Parameters
    ----------
    sample_rate: int
        Target sample rate.
    mono : int, optional
        Convert multi-channel to mono. Defaults to True.

    Usage
    -----
    >>> audio = Audio(sample_rate=16000)
    >>> samples = audio("/path/to/audio.wav")

    # on-the-fly resampling
    >>> original_sample_rate = 44100
    >>> two_seconds_stereo = torch.rand(2, 2 * original_sample_rate)
    >>> samples = audio({"samples": two_seconds_stereo, "sample_rate": original_sample_rate})
    >>> assert samples.shape[1] == 2 * 16000
    filereturnc                    t        | t              r{d| v rg| d   }t        |j                        dk7  s|j                  d   |j                  d   kD  rt	        d      | j                  dd       }|t	        d      yd	| v ryt	        d
      y)Nsamples   r      z='samples' must be provided as a (channel, time) torch.Tensor.sample_ratez4'samples' must be provided with their 'sample_rate'.Taudioz1either 'audio' or 'samples' key must be provided.)
isinstancedictlenshape
ValueErrorget)r	   r   r   s      s/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torch_audiomentations/utils/io.pyis_validzAudio.is_valid.   s    dD!D y/w}}%*gmmA.>qAQ.Q$W  #hh}d;&$N  D !!TUU    r   c                 p    | j                         j                  dd      j                         }| |dz   z  S )a  Power-normalize samples

        Parameters
        ----------
        samples : (..., time) Tensor
            Single (or multichannel) samples or batch of samples

        Returns
        -------
        samples: (..., time) Tensor
            Power-normalized samples
        Tdimkeepdimg:0yE>)squaremeansqrt)r   rmss     r   rms_normalizezAudio.rms_normalizeH   s8     nn##D#9>>@#*%%r   	file_pathc                     t        j                  t        |             }t        |      t        u r!|\  }}|j
                  }|j                  }||fS |j                  }|j                  }||fS )z"Return (num_samples, sample_rate).)	
torchaudioinfostrtypetuplelengthrate
num_framesr   )r$   r'   sieinum_samplesr   s         r   get_audio_metadatazAudio.get_audio_metadataY   sm     s9~. :FB))K''K K'' //K**KK''r   c                    | j                  |       t        |t              r4d|v r|d   j                  d   }|d   }n,| j	                  |d         \  }}n| j	                  |      \  }}t        j                  || j                  z  |z        S )zTNumber of samples (in target sample rate)

        :param file: audio file

        r   r   r   r   )r   r   r   r   r1   mathceilr   )selfr	   r0   r   s       r   get_num_sampleszAudio.get_num_samplesh   s     	ddD!D "9o33A6"=1 ,0+B+B4=+Q([ (,'>'>t'D$Kyyt'7'77+EFFr   r   monoc                 >    t         |           || _        || _        y )N)super__init__r   r7   )r5   r   r7   	__class__s      r   r:   zAudio.__init__   s    &	r   c                     | j                   r%|j                  d   dkD  r|j                  dd      }| j                  |k7  r+t        j
                  j                  ||| j                        }|S )a2  Downmix and resample

        Parameters
        ----------
        samples : (channel, time) Tensor
            Samples.
        sample_rate : int
            Original sample rate.

        Returns
        -------
        samples : (channel, time) Tensor
            Remixed and resampled samples
        r   r   Tr   )r7   r   r    r   r&   
functionalresample)r5   r   r   s      r   downmix_and_resamplezAudio.downmix_and_resample   sg    " 99q)A-llq$l7G {* ++44d&6&6G r   sample_offsetr0   c                    | j                  |       d}t        |t              red|v r,|d   }|d   }|j                  d   }|j	                  dd      }nVt        |d         }| j                  |      \  }}|j	                  dd      }n!t        |      }| j                  |      \  }}d}t        ||z  | j                  z        }	|||	z
  }
nt        ||z  | j                  z        }
|	|
z   |kD  r
t               |	 t        j                  |	|
      \  }}n|dd|	|	|
z   f   }|||dz
  |ddf   }| j                  ||      }|o|j                  d	   |kD  r|ddd|f   }|S |j                  d	   |k  r>||j                  d	   z
  }t        j                   j"                  j%                  |d
|f      }|S # t        $ r t        d      w xY w)a  

        Parameters
        ----------
        file : AudioFile
            Audio file.
        sample_offset : int, optional
            Start loading at this `sample_offset` sample. Defaults ot 0.
        num_samples : int, optional
            Load that many samples. Defaults to load up to the end of the file.

        Returns
        -------
        samples : (time, channel) torch.Tensor
            Samples

        Nr   r   r   channelr   )frame_offsetr-   z~It looks like you are using an unsupported version of torchaudio. If you have 0.6 or older, please upgrade to a newer version.r   r   )r   r   r   r   r   r(   r1   roundr   r   r&   load	TypeError	Exceptionr?   torchnnr=   pad)r5   r	   r@   r0   original_samplesoriginal_sample_rateoriginal_total_num_samplesrB   
audio_pathoriginal_sample_offsetoriginal_num_samplesoriginal_data_resultdiffs                  r   __call__zAudio.__call__   sK   * 	ddD!D #'	? '+M':$-=-C-CA-F*((9d3 !g/
 ++J7.(((9d3 TJ?C?V?V@<&(< G!&0043C3CC"
 #=@V#V #(22T5E5EE$  "$88;UU,#
#-??!73$ q -),BEY,YYYM )'A+*?*BCM**=:NO"||B+-<K<0
 	 b!K/"V\\"%55,,00!TC1  T s   =F< <G)T)r   N)__name__
__module____qualname____doc__staticmethod	AudioFileboolr   r   r#   r   r(   r   r*   r1   intr6   r:   r?   rU   __classcell__)r;   s   @r   r   r      s    * y T  2 &v && & &  (eCI&6 (5 ( (GI G# G2C t 
F   : KO^^.1^DG^	^r   r   )pathlibr   typingr   r   rH   r&   r   r3   r   r[   r    r   r   <module>rb      s9         $d"#	
h hr   