
    pip4                     T   d Z ddlZddlmZmZmZmZ ddlZ	 	 	 	 	 	 	 ddeeeej                  f   de
de
deded	ee   d
e
dee   deej                  e
f   fdZ	 	 	 	 	 	 	 ddeeej                  f   dej                  de
ded	ee   dee   dee
   d
e
dee   deeee
f      ddfdZy)z&TorchCodec integration for TorchAudio.    N)BinaryIOOptionalTupleUnionuriframe_offset
num_frames	normalizechannels_firstformatbuffer_sizebackendreturnc                 "   	 ddl m} |sddl}
|
j	                  dt
        d       |dk7  rddl}
|
j	                  d	t
        d       |ddl}
|
j	                  d
t
        d       |ddl}
|
j	                  dt
        d       	  ||       }|j                  j                  }|t        d      	 |j                         }|j                  }|dkD  rh||j                  d   k\  rK|r|j                  d   dfnd|j                  d   f}t        j                  |t        j                        |fS |dd|df   }|dk(  rK|r|j                  d   dfnd|j                  d   f}t        j                  |t        j                        |fS |dkD  r|ddd|f   }|s|j!                  dd      }||fS # t        $ r}	t        d      |	d}	~	ww xY w# t        $ r}	t        d|  d|	       |	d}	~	ww xY w# t        $ r}	t        d|	       |	d}	~	ww xY w)a  Load audio data from source using TorchCodec's AudioDecoder.

    .. note::

        This function supports the same API as :func:`~torchaudio.load`, and
        relies on TorchCodec's decoding capabilities under the hood. It is
        provided for convenience, but we do recommend that you port your code to
        natively use ``torchcodec``'s ``AudioDecoder`` class for better
        performance:
        https://docs.pytorch.org/torchcodec/stable/generated/torchcodec.decoders.AudioDecoder.
        As of TorchAudio 2.9, :func:`~torchaudio.load` relies on
        :func:`~torchaudio.load_with_torchcodec`. Note that some parameters of
        :func:`~torchaudio.load`, like ``normalize``, ``buffer_size``, and
        ``backend``, are ignored by :func:`~torchaudio.load_with_torchcodec`.
        To install torchcodec, follow the instructions at https://github.com/pytorch/torchcodec#installing-torchcodec.


    Args:
        uri (path-like object or file-like object):
            Source of audio data. The following types are accepted:

            * ``path-like``: File path or URL.
            * ``file-like``: Object with ``read(size: int) -> bytes`` method.

        frame_offset (int, optional):
            Number of samples to skip before start reading data.
        num_frames (int, optional):
            Maximum number of samples to read. ``-1`` reads all the remaining samples,
            starting from ``frame_offset``.
        normalize (bool, optional):
            TorchCodec always returns normalized float32 samples. This parameter
            is ignored and a warning is issued if set to False.
            Default: ``True``.
        channels_first (bool, optional):
            When True, the returned Tensor has dimension `[channel, time]`.
            Otherwise, the returned Tensor's dimension is `[time, channel]`.
        format (str or None, optional):
            Format hint for the decoder. May not be supported by all TorchCodec
            decoders. (Default: ``None``)
        buffer_size (int, optional):
            Not used by TorchCodec AudioDecoder. Provided for API compatibility.
        backend (str or None, optional):
            Not used by TorchCodec AudioDecoder. Provided for API compatibility.

    Returns:
        (torch.Tensor, int): Resulting Tensor and sample rate.
        Always returns float32 tensors. If ``channels_first=True``, shape is
        `[channel, time]`, otherwise `[time, channel]`.

    Raises:
        ImportError: If torchcodec is not available.
        ValueError: If unsupported parameters are used.
        RuntimeError: If TorchCodec fails to decode the audio.

    Note:
        - TorchCodec always returns normalized float32 samples, so the ``normalize``
          parameter has no effect.
        - The ``buffer_size`` and ``backend`` parameters are ignored.
        - Not all audio formats supported by torchaudio backends may be supported
          by TorchCodec.
    r   )AudioDecoderz`TorchCodec is required for load_with_torchcodec. Please install torchcodec to use this function.NznTorchCodec AudioDecoder always returns normalized float32 samples. The 'normalize=False' parameter is ignored.   
stacklevel   zCThe 'buffer_size' parameter is not used by TorchCodec AudioDecoder.z?The 'backend' parameter is not used by TorchCodec AudioDecoder.zCThe 'format' parameter is not supported by TorchCodec AudioDecoder.z"Failed to create AudioDecoder for : z3Unable to determine sample rate from audio metadataz Failed to decode audio samples:    )dtype)torchcodec.decodersr   ImportErrorwarningswarnUserWarning	ExceptionRuntimeErrormetadatasample_rateget_all_samplesdatashapetorchzerosfloat32	transpose)r   r   r	   r
   r   r   r   r   r   er   decoderr!   audio_samplesr#   empty_shapes                   X/opt/services/ai/voice_agent/venv/lib/python3.12/site-packages/torchaudio/_torchcodec.pyload_with_torchcodecr.   	   sG   P4 :	 	 	
 d[]huvwWYdqrs[]huvwSs#
 ""..KPQQJ//1 D a4::a=(0>4::a=!,Q

STDVK;;{%--@+MMA|}$%Q,:tzz!}a(DJJqM@R{{;emm<kII	aA{
{N# ~~a#O  q
	D  S?uBqcJKQRRS  J=aSABIJsG   F1 G 0G1 1	G:GG	G.G))G.1	H:H		Hsrcr!   encodingbits_per_samplecompressionc
                    	 ddl m}
 |ddl}|j	                  dt
        d       |ddl}|j	                  dt
        d       |ddl}|j	                  d	t
        d       |d
k7  rddl}|j	                  dt
        d       |ddl}|j	                  dt
        d       t        |t        j                        st        dt        |             |j                  t        j                  k7  r|j                         }|dk  rt        d|       |j                  dk(  r6|r|j                  d      }nb|j                  d      j!                  dd      }n@|j                  dk(  r|r|}n,|j!                  dd      }nt        d|j                   d      	  |
||      }d}|	Kt        |	t&        t        f      rt'        |	      }n)ddl}|j	                  dt        |	       dt
        d       	 |j)                  | |       y# t        $ r}t        d      |d}~ww xY w# t"        $ r}t%        d|       |d}~ww xY w# t"        $ r}t%        d|  d|       |d}~ww xY w)a  Save audio data to file using TorchCodec's AudioEncoder.

    .. note::

        This function supports the same API as :func:`~torchaudio.save`, and
        relies on TorchCodec's encoding capabilities under the hood. It is
        provided for convenience, but we do recommend that you port your code to
        natively use ``torchcodec``'s ``AudioEncoder`` class for better
        performance:
        https://docs.pytorch.org/torchcodec/stable/generated/torchcodec.encoders.AudioEncoder.
        As of TorchAudio 2.9, :func:`~torchaudio.save` relies on
        :func:`~torchaudio.save_with_torchcodec`. Note that some parameters of
        :func:`~torchaudio.save`, like ``format``, ``encoding``,
        ``bits_per_sample``, ``buffer_size``, and ``backend``, are ignored by
        are ignored by :func:`~torchaudio.save_with_torchcodec`.
        To install torchcodec, follow the instructions at https://github.com/pytorch/torchcodec#installing-torchcodec.

    This function provides a TorchCodec-based alternative to torchaudio.save
    with the same API. TorchCodec's AudioEncoder provides efficient encoding
    with FFmpeg under the hood.

    Args:
        uri (path-like object):
            Path to save the audio file. The file extension determines the format.

        src (torch.Tensor):
            Audio data to save. Must be a 1D or 2D tensor with float32 values
            in the range [-1, 1]. If 2D, shape should be [channel, time] when
            channels_first=True, or [time, channel] when channels_first=False.

        sample_rate (int):
            Sample rate of the audio data.

        channels_first (bool, optional):
            Indicates whether the input tensor has channels as the first dimension.
            If True, expects [channel, time]. If False, expects [time, channel].
            Default: True.

        format (str or None, optional):
            Audio format hint. Not used by TorchCodec (format is determined by
            file extension). A warning is issued if provided.
            Default: None.

        encoding (str or None, optional):
            Audio encoding. Not fully supported by TorchCodec AudioEncoder.
            A warning is issued if provided. Default: None.

        bits_per_sample (int or None, optional):
            Bits per sample. Not directly supported by TorchCodec AudioEncoder.
            A warning is issued if provided. Default: None.

        buffer_size (int, optional):
            Not used by TorchCodec AudioEncoder. Provided for API compatibility.
            A warning is issued if not default value. Default: 4096.

        backend (str or None, optional):
            Not used by TorchCodec AudioEncoder. Provided for API compatibility.
            A warning is issued if provided. Default: None.

        compression (float, int or None, optional):
            Compression level or bit rate. Maps to bit_rate parameter in
            TorchCodec AudioEncoder. Default: None.

    Raises:
        ImportError: If torchcodec is not available.
        ValueError: If input parameters are invalid.
        RuntimeError: If TorchCodec fails to encode the audio.

    Note:
        - TorchCodec AudioEncoder expects float32 samples in [-1, 1] range.
        - Some parameters (format, encoding, bits_per_sample, buffer_size, backend)
          are not used by TorchCodec but are provided for API compatibility.
        - The output format is determined by the file extension in the uri.
        - TorchCodec uses FFmpeg under the hood for encoding.
    r   )AudioEncoderz`TorchCodec is required for save_with_torchcodec. Please install torchcodec to use this function.NzjThe 'format' parameter is not used by TorchCodec AudioEncoder. Format is determined by the file extension.r   r   zKThe 'encoding' parameter is not fully supported by TorchCodec AudioEncoder.zUThe 'bits_per_sample' parameter is not directly supported by TorchCodec AudioEncoder.r   zCThe 'buffer_size' parameter is not used by TorchCodec AudioEncoder.z?The 'backend' parameter is not used by TorchCodec AudioEncoder.z'Expected src to be a torch.Tensor, got z"sample_rate must be positive, got r   zExpected 1D or 2D tensor, got zD tensor)r!   zFailed to create AudioEncoder: zUnsupported compression type z<. TorchCodec AudioEncoder expects int or float for bit_rate.)bit_ratezFailed to save audio to r   )torchcodec.encodersr4   r   r   r   r   
isinstancer%   Tensor
ValueErrortyper   r'   floatndim	unsqueezer(   r   r   intto_file)r   r/   r!   r   r   r0   r1   r   r   r2   r4   r)   r   r#   encoderr5   s                   r-   save_with_torchcodecrA      s   p4 :	 	 	
 Y[fst 	 	
 "c 	 	
 d[]huvwWYdqrs c5<<(B49+NOO
yyEMM!iika=k]KLL xx1}==#D ==#--a3D	QD==A&D9#((8LMMIt=
 HkC<0;'HMM/[0A/B CM M	  Ih/w  q
	N  I<QC@AqHI*  I5cU"QC@AqHIsG   H 
H# 2I 	H HH #	I ,H;;I 	I#II#)r   TTNr   N)TNNNr   NN)__doc__ostypingr   r   r   r   r%   strPathLiker>   boolr8   r.   r;   rA        r-   <module>rK      s   , 	 3 3 
  !Q	xbkk)	*QQ Q 	Q
 Q SMQ Q c]Q 5<<Qp   "%)!/3wI	sBKK	 wI	wI wI 	wI
 SMwI smwI c]wI wI c]wI %s
+,wI 
wIrJ   