
    ShH|                     r   d Z ddlmZmZ ddlZddlmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlZ	 ddlZdZn# e$ rZd	ZY dZ[ndZ[ww xY w	 dd
lmZ eZn# e$ rZej        dk    reZY dZ[ndZ[ww xY wg dZ G d d          Z G d d          Z G d de          Z G d d          Z G d de          ZdS )aA  
Class summary
=============

.. autosummary::

        DataSource
        StringDataSource
        ADSFactory
        ADSFactory.AudioDataSource
        ADSFactory.ADSDecorator
        ADSFactory.OverlapADS
        ADSFactory.LimiterADS
        ADSFactory.RecorderADS
        DataValidator
        AudioEnergyValidator

    )ABCMetaabstractmethodN)array   )
Rewindable	from_fileBufferAudioSourcePyAudioSource)DuplicateArgumentTF)str)   r   )
DataSourceDataValidatorStringDataSource
ADSFactoryAudioEnergyValidatorc                   ,    e Zd ZdZeZed             ZdS )r   z
    Base class for objects passed to :func:`auditok.core.StreamTokenizer.tokenize`.
    Subclasses should implement a :func:`DataSource.read` method.
    c                     dS )zp
        Read a piece of data read from this source.
        If no more data is available, return None.
        N selfs    R/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/auditok/util.pyreadzDataSource.read6             N)__name__
__module____qualname____doc__r   __metaclass__r   r   r   r   r   r   r   /   s>          M  ^  r   r   c                   ,    e Zd ZdZeZed             ZdS )r   z
    Base class for a validator object used by :class:`.core.StreamTokenizer` to check
    if read data is valid.
    Subclasses should implement :func:`is_valid` method.
    c                     dS )z/
        Check whether `data` is valid
        Nr   r   datas     r   is_validzDataValidator.is_validF   r   r   N)r   r   r   r   r   r    r   r%   r   r   r   r   r   >   s>         
 M  ^  r   r   c                   $    e Zd ZdZd Zd Zd ZdS )r   a?  
    A class that represent a :class:`DataSource` as a string buffer.
    Each call to :func:`DataSource.read` returns on character and moves one step forward.
    If the end of the buffer is reached, :func:`read` returns None.
   
    :Parameters:
        
        `data` : 
            a basestring object.
     
    c                 L    d | _         d| _        |                     |           d S Nr   )_data_currentset_datar#   s     r   __init__zStringDataSource.__init__Y   s(    
dr   c                     | j         t          | j                  k    rdS | xj         dz  c_         | j        | j         dz
           S )z
        Read one character from buffer.
        
        :Returns:
        
            Current character or None if end of buffer is reached
        Nr   )r*   lenr)   r   s    r   r   zStringDataSource.read`   sB     =C
OO++4z$-!+,,r   c                 j    t          |t                    st          d          || _        d| _        dS )z
        Set a new data buffer.
        
        :Parameters:
        
            `data` : a basestring object 
                New data buffer.
        z#data must an instance of basestringr   N)
isinstance
basestring
ValueErrorr)   r*   r#   s     r   r+   zStringDataSource.set_datan   s8     $
++ 	DBCCC
r   N)r   r   r   r   r,   r   r+   r   r   r   r   r   L   sK        
 
  - - -    r   r   c                       e Zd ZdZed             Zed             Z G d de          Z G d de          Z	 G d d	e	          Z
 G d
 de	          Z G d de	          ZdS )r   a  
    Factory class that makes it easy to create an :class:`ADSFactory.AudioDataSource` object that implements
    :class:`DataSource` and can therefore be passed to :func:`auditok.core.StreamTokenizer.tokenize`.
    
    Whether you read audio data from a file, the microphone or a memory buffer, this factory
    instantiates and returns the right :class:`ADSFactory.AudioDataSource` object.
    
    There are many other features you want your :class:`ADSFactory.AudioDataSource` object to have, such as: 
    memorize all read audio data so that you can rewind and reuse it (especially useful when 
    reading data from the microphone), read a fixed amount of data (also useful when reading 
    from the microphone), read overlapping audio frames (often needed when dosing a spectral
    analysis of data).
    
    :func:`ADSFactory.ads` automatically creates and return object with the desired behavior according
    to the supplied keyword arguments. 
     
    c                    | D ](}|dvr"t          d                    |                    )d| v rd| v rt          d          d| v rd| v rt          d          d	| v rd
| v rt          d          d| v rd| v rt          d          d| v rd| v rt          d          d| v rd| v rt          d          d| v rd| v rt          d          d| v rd| v rt          d          d| v rd| v rt          d          d| v rd| v rt          d           d!| v rd"| v rt          d#          d$| v rd%| v rt          d&          d'| v rd(| v rt          d)          |                     dd           p|                     dd           | d<   |                     dd           p|                     dd           | d<   |                     d	d           p|                     d
d           | d
<   |                     dd           p|                     dd           | d<   |                     dd           p|                     dd           | d<   |                     dd           p|                     dd           | d<   |                     dd           p|                     dd           | d<   |                     dd           p|                     dd           | d<   |                     d'd*          }|s:|                     d(d*          }t	          |t
                    st          d+          || d(<   d| v sd,| v r/|                     dd           p|                     d,d           | d<   d| v sd| v r/|                     dd           p|                     dd           | d<   d!| v sd"| v r/|                     d!d           p|                     d"d           | d!<   d$| v sd%| v r1|                     d$d           p|                     d%d           | d$<   d S d S )-N)	block_durhop_dur
block_sizehop_sizemax_timerecordaudio_sourcefilenamedata_bufferframes_per_buffersampling_ratesample_widthchannelssrswchasrcfnfpbdbmtrecbdhdbshszInvalid argument: {0}r5   rK   z6Either 'block_dur' or 'bd' must be specified, not bothr6   rL   z4Either 'hop_dur' or 'hd' must be specified, not bothr7   rM   z7Either 'block_size' or 'bs' must be specified, not bothr8   rN   z5Either 'hop_size' or 'hs' must be specified, not bothr9   rI   z5Either 'max_time' or 'mt' must be specified, not bothr;   rE   z;Either 'audio_source' or 'asrc' must be specified, not bothr<   rF   z5Either 'filename' or 'fn' must be specified, not bothr=   rH   z5Either 'filename' or 'db' must be specified, not bothr>   fbbz?Either 'frames_per_buffer' or 'fpb' must be specified, not bothr?   rB   z:Either 'sampling_rate' or 'sr' must be specified, not bothr@   rC   z9Either 'sample_width' or 'sw' must be specified, not bothrA   rD   z5Either 'channels' or 'ch' must be specified, not bothr:   rJ   z4Either 'record' or 'rec' must be specified, not bothFz'record' must be a booleanrG   )r2   formatr   popr0   bool	TypeError)kwargskr:   s      r   _check_normalize_argsz ADSFactory._check_normalize_args   s     	D 	DA 8 8 8 !!8!?!?!B!BCCC	8 &  TV^^#$\]]]46>>#$Z[[[6!!dfnn#$]^^^DFNN#$[\\\DFNN#$[\\\V##&(8(8#$abbbDFNN#$[\\\F""tv~~#$[\\\&((Uf__#$effff$$#$`aaaV###$_```DFNN#$[\\\v%6//#$Z[[[ zz+t44N

48N8Ntzz)T22Lfjjt6L6Ltzz,55OD$9O9Otzz*d33Mvzz$7M7Mtzz*d33Mvzz$7M7MtND99UVZZPT=U=Uvzz*d33Mvzz$7M7Mtzz-66P&**T4:P:PtHe,, 	>ZZu--Ffd++ > <===u &((EVOO*0**5H$*O*O*jSYS]S]^ceiSjSjF&'f$$&,jj$&G&G&a6::VZ\`KaKaF?#V##tv~~%+ZZ%E%E%_TXZ^I_I_F>"46>>!'J!=!=!WDRVAWAWF: $2>r   c                     |                                  } t                              |            |                     d          }|                     d          }|                     d          }|                     d          }|                     d          }|                     d          }|                     d          }|                     d          }|                     d	          }	|||fdk    rt	          d          n@|!|t	          d          t          |          }n|t          dd|i| }nt          di | }|6|t          d          t          |
                                |z            }n&|$t          |
                                dz            }t                              ||          }
|t                              |
|          }
|	rt                              |
          }
|5|t          d          t          |
                                |z            }|=|dk    s||k    rt          d          ||k     rt                              |
|          }
|
S )a   
        Create an return an :class:`ADSFactory.AudioDataSource`. The type and behavior of the object is the result
        of the supplied parameters.
        
        :Parameters:
        
        *No parameters* :  
           read audio data from the available built-in microphone with the default parameters.
           The returned :class:`ADSFactory.AudioDataSource` encapsulate an :class:`io.PyAudioSource` object and hence 
           it accepts the next four parameters are passed to use instead of their default values.
        
        `sampling_rate`, `sr` : *(int)*
            number of samples per second. Default = 16000.
        
        `sample_width`, `sw` : *(int)*
            number of bytes per sample (must be in (1, 2, 4)). Default = 2
        
        `channels`, `ch` : *(int)*
            number of audio channels. Default = 1 (only this value is currently accepted)  
            
        `frames_per_buffer`, `fpb` : *(int)*
            number of samples of PyAudio buffer. Default = 1024.
        
        `audio_source`, `asrc` : an `AudioSource` object
            read data from this audio source
            
        `filename`, `fn` : *(string)*
            build an `io.AudioSource` object using this file (currently only wave format is supported)
            
        `data_buffer`, `db` : *(string)*
            build an `io.BufferAudioSource` using data in `data_buffer`. If this keyword is used,
            `sampling_rate`, `sample_width` and `channels` are passed to `io.BufferAudioSource`
            constructor and used instead of default values.
            
        `max_time`, `mt` : *(float)*
            maximum time (in seconds) to read. Default behavior: read until there is no more data
            available. 
         
        `record`, `rec` : *(bool)*
            save all read data in cache. Provide a navigable object which boasts a `rewind` method.
            Default = False.
        
        `block_dur`, `bd` : *(float)*
            processing block duration in seconds. This represents the quantity of audio data to return 
            each time the :func:`read` method is invoked. If `block_dur` is 0.025 (i.e. 25 ms) and the sampling
            rate is 8000 and the sample width is 2 bytes, :func:`read` returns a buffer of 0.025 * 8000 * 2 = 400
            bytes at most. This parameter will be looked for (and used if available) before `block_size`.
            If neither parameter is given, `block_dur` will be set to 0.01 second (i.e. 10 ms)
            
            
        `hop_dur`, `hd` : *(float)*
            quantity of data to skip from current processing window. if `hop_dur` is supplied then there
            will be an overlap of `block_dur` - `hop_dur` between two adjacent blocks. This
            parameter will be looked for (and used if available) before `hop_size`. If neither parameter
            is given, `hop_dur` will be set to `block_dur` which means that there will be no overlap
            between two consecutively read blocks.
             
        `block_size`, `bs` : *(int)*
            number of samples to read each time the `read` method is called. Default: a block size
            that represents a window of 10ms, so for a sampling rate of 16000, the default `block_size`
            is 160 samples, for a rate of 44100, `block_size` = 441 samples, etc.
        
        `hop_size`, `hs` : *(int)*
            determines the number of overlapping samples between two adjacent read windows. For a
            `hop_size` of value *N*, the overlap is `block_size` - *N*. Default : `hop_size` = `block_size`,
            means that there is no overlap.
            
        :Returns:
        
        An AudioDataSource object that has the desired features.
        
        :Exampels:
        
        1. **Create an AudioDataSource that reads data from the microphone (requires Pyaudio) with default audio parameters:**
        
        .. code:: python
        
            from auditok import ADSFactory
            ads = ADSFactory.ads()
            ads.get_sampling_rate()
            16000
            ads.get_sample_width()
            2
            ads.get_channels()
            1
        
        
        2. **Create an AudioDataSource that reads data from the microphone with a sampling rate of 48KHz:**
        
        .. code:: python
        
            from auditok import ADSFactory
            ads = ADSFactory.ads(sr=48000)
            ads.get_sampling_rate()
            48000
        
        3. **Create an AudioDataSource that reads data from a wave file:**
        
        .. code:: python
        
            import auditok
            from auditok import ADSFactory
            ads = ADSFactory.ads(fn=auditok.dataset.was_der_mensch_saet_mono_44100_lead_trail_silence)
            ads.get_sampling_rate()
            44100
            ads.get_sample_width()
            2
            ads.get_channels()
            1
        
        4. **Define size of read blocks as 20 ms**
        
        .. code:: python
        
            import auditok
            from auditok import ADSFactory
            '''
            we know samling rate for previous file is 44100 samples/second
            so 10 ms are equivalent to 441 samples and 20 ms to 882
            '''
            block_size = 882
            ads = ADSFactory.ads(bs = 882, fn=auditok.dataset.was_der_mensch_saet_mono_44100_lead_trail_silence)
            ads.open()
            # read one block
            data = ads.read()
            ads.close()
            len(data)
            1764
            assert len(data) ==  ads.get_sample_width() * block_size
        
        5. **Define block size as a duration (use block_dur or bd):**
        
        .. code:: python
        
            import auditok
            from auditok import ADSFactory
            dur = 0.25 # second
            ads = ADSFactory.ads(bd = dur, fn=auditok.dataset.was_der_mensch_saet_mono_44100_lead_trail_silence)
            '''
            we know samling rate for previous file is 44100 samples/second
            for a block duration of 250 ms, block size should be 0.25 * 44100 = 11025
            '''
            ads.get_block_size()
            11025
            assert ads.get_block_size() ==  int(0.25 * 44100)
            ads.open()
            # read one block
            data = ads.read()
            ads.close()
            len(data)
            22050
            assert len(data) ==  ads.get_sample_width() * ads.get_block_size()
            
        6. **Read overlapping blocks (one of hope_size, hs, hop_dur or hd > 0):**
        
        For better readability we'd better use :class:`auditok.io.BufferAudioSource` with a string buffer:

        .. code:: python

            import auditok
            from auditok import ADSFactory
            '''
            we supply a data beffer instead of a file (keyword 'bata_buffer' or 'db')
            sr : sampling rate = 16 samples/sec
            sw : sample width = 1 byte
            ch : channels = 1
            '''
            buffer = "abcdefghijklmnop" # 16 bytes = 1 second of data
            bd = 0.250 # block duration = 250 ms = 4 bytes
            hd = 0.125 # hop duration = 125 ms = 2 bytes 
            ads = ADSFactory.ads(db = "abcdefghijklmnop", bd = bd, hd = hd, sr = 16, sw = 1, ch = 1)
            ads.open()
            ads.read()
            'abcd'
            ads.read()
            'cdef'
            ads.read()
            'efgh'
            ads.read()
            'ghij'
            data = ads.read()
            assert data == 'ijkl'
        
        7. **Limit amount of read data (use max_time or mt):**
        
        .. code:: python
        
            '''
            We know audio file is larger than 2.25 seconds
            We want to read up to 2.25 seconds of audio data
            '''
            ads = ADSFactory.ads(mt = 2.25, fn=auditok.dataset.was_der_mensch_saet_mono_44100_lead_trail_silence)
            ads.open()
            data = []
            while True:
                d = ads.read()
                if d is None:
                    break
                data.append(d)
                
            ads.close()
            data = b''.join(data)
            assert len(data) == int(ads.get_sampling_rate() * 2.25 * ads.get_sample_width() * ads.get_channels())
        rK   rL   rM   rN   rI   rE   rF   rH   rJ   N)NNzYou should provide one of 'audio_source', 'filename' or 'data_buffer'                 keyword parameters. 'audio_source' will be usedzqYou should provide one of 'filename' or 'data_buffer'                 keyword parameters. 'filename' will be usedr=   z=Either 'block_dur' or 'block_size' can be specified, not bothd   r;   r7   )adsr9   )rZ   z9Either 'hop_dur' or 'hop_size' can be specified, not bothr   z&hop_size must be > 0 and <= block_size)rZ   r8   r   )copyr   rV   rQ   Warningr   r	   r
   r   intget_sampling_rateAudioDataSource
LimiterADSRecorderADSr2   
OverlapADS)rT   r5   r6   r7   r8   r9   r;   r<   r=   r:   rZ   s              r   rZ   zADSFactory.ads   s   b  	((000JJt$$	**T""ZZ%%
::d##::d##zz&))::d##jj&&E"" #+&,66 B C C C 7
 !& > ? ? ?$X..LL $,QQ;Q&QQLL )22622L  %'(ghhh !?!?!A!AI!MNN

\;;==CDDJ ((lz(ZZ ''C('CCC  	2((S(11C #'(cddd|==??'IJJ1}}J!6!6 !IJJJ*$$ ++h+GG
r   c                   f    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd ZdS )ADSFactory.AudioDataSourcez
        Base class for AudioDataSource objects.
        It inherits from DataSource and encapsulates an AudioSource object.
        c                 "    || _         || _        d S NrY   )r   r;   r7   s      r   r,   z#ADSFactory.AudioDataSource.__init__  s     ,D(DOOOr   c                     | j         S rf   r7   r   s    r   get_block_sizez)ADSFactory.AudioDataSource.get_block_size  s
    ?"r   c                     || _         d S rf   rh   )r   sizes     r   set_block_sizez)ADSFactory.AudioDataSource.set_block_size  s    "DOOOr   c                     | j         S rf   r;   r   s    r   get_audio_sourcez+ADSFactory.AudioDataSource.get_audio_source  s    $$r   c                     || _         d S rf   rn   r   r;   s     r   set_audio_sourcez+ADSFactory.AudioDataSource.set_audio_source  s     ,Dr   c                 8    | j                                          d S rf   )r;   openr   s    r   rt   zADSFactory.AudioDataSource.open  s    ""$$$$$r   c                 8    | j                                          d S rf   )r;   closer   s    r   rv   z ADSFactory.AudioDataSource.close  s    ##%%%%%r   c                 4    | j                                         S rf   )r;   is_openr   s    r   rx   z"ADSFactory.AudioDataSource.is_open  s    $,,...r   c                 4    | j                                         S rf   )r;   r^   r   s    r   r^   z,ADSFactory.AudioDataSource.get_sampling_rate"  s    $66888r   c                 4    | j                                         S rf   )r;   get_sample_widthr   s    r   r{   z+ADSFactory.AudioDataSource.get_sample_width%  s    $55777r   c                 4    | j                                         S rf   )r;   get_channelsr   s    r   r}   z'ADSFactory.AudioDataSource.get_channels(  s    $11333r   c                     t          | j        t                    r| j                                         d S t	          d          )NzAudio source is not rewindable)r0   r;   r   rewind	Exceptionr   s    r   r   z!ADSFactory.AudioDataSource.rewind,  sB    $+Z88 B!((***** @AAAr   c                 6    t          | j        t                    S rf   )r0   r;   r   r   s    r   is_rewindablez(ADSFactory.AudioDataSource.is_rewindable4  s    d/<<<r   c                 @    | j                             | j                  S rf   )r;   r   r7   r   s    r   r   zADSFactory.AudioDataSource.read8  s    $))$/:::r   N)r   r   r   r   r,   ri   rl   ro   rr   rt   rv   rx   r^   r{   r}   r   r   r   r   r   r   r_   rd     s        	 	
	) 	) 	)
	# 	# 	#	# 	# 	#	% 	% 	%	- 	- 	-	% 	% 	%	& 	& 	&	/ 	/ 	/	9 	9 	9	8 	8 	8	4 	4 	4	B 	B 	B	= 	= 	=	; 	; 	; 	; 	;r   r_   c                   J    e Zd ZdZeZd Zd Zd Zd Z	d Z
ed             ZdS )	ADSFactory.ADSDecoratorzC
        Base decorator class for AudioDataSource objects.
        c                 F   || _         | j         j        | _        | j         j        | _        | j         j        | _        | j         j        | _        | j         j        | _        | j         j        | _        | j         j        | _        | j         j        | _        | j         j	        | _	        d S rf   )
rZ   ri   rl   ro   rt   rv   rx   r^   r{   r}   r   rZ   s     r   r,   z ADSFactory.ADSDecorator.__init__B  s    DH"&("9D"&("9D$(H$=D!DIDJ8+DL%)X%?D"$(H$=D! $ 5Dr   c                     | j         j        S rf   )rZ   r   r   s    r   r   z%ADSFactory.ADSDecorator.is_rewindableO  s    8))r   c                 `    | j                                          |                                  d S rf   )rZ   r   _reinitr   s    r   r   zADSFactory.ADSDecorator.rewindR  s%    HOOLLNNNNNr   c                 b    | j                             |           |                                  d S rf   )rZ   rr   r   rq   s     r   rr   z(ADSFactory.ADSDecorator.set_audio_sourceV  s)    H%%l333LLNNNNNr   c                     | j                                         s/| j                                          |                                  d S d S rf   )rZ   rx   rt   r   r   s    r   rt   zADSFactory.ADSDecorator.openZ  sB    8##%%  r   c                     d S rf   r   r   s    r   r   zADSFactory.ADSDecorator._reinit_  s    Dr   N)r   r   r   r   r   r    r,   r   r   rr   rt   r   r   r   r   r   ADSDecoratorr   <  s        	 	  	6 	6 	6	* 	* 	*	 	 		 	 		 	 	
 
	 	 
	 	 	r   r   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )ADSFactory.OverlapADSzg
        A class for AudioDataSource objects that can read and return overlapping audio frames
        c                     t           j                             |           |dk    s|                                 k    rt	          d          | _                                          _                                           fd}d S )Nr   z\hop_size must be either 'None' or                  between 1 and block_size (both inclusive)c                       j         S rf   )_actual_block_sizer   s   r   _get_block_sizez7ADSFactory.OverlapADS.__init__.<locals>._get_block_sizet  s    ..r   )r   r   r,   ri   r2   r8   r   r   )r   rZ   r8   r   s   `   r   r,   zADSFactory.OverlapADS.__init__i  s    #,,T37771}}4+>+>+@+@ @ @  "< = = =$DM&*&9&9&;&;D#LLNNN/ / / / / / /r   c                     | j                                         }|d S t          |          | j        k    r|| j        d          | _        | j                             | j                   | j        | _        |S rf   )rZ   r   r.   _hop_size_bytes_cacherl   r8   _read_next_blocksr   blocks     r   _read_first_blockz'ADSFactory.OverlapADS._read_first_blockx  so    HMMOOE}t 5zzD000#D$8$9$9: H##DM222.DILr   c                     | j                                         }|d S | j        |z   }t          |          | j        k    r|| j        d          | _        nd | _        |S rf   )rZ   r   r   r.   _block_size_bytesr   r   s     r   r   z'ADSFactory.OverlapADS._read_next_blocks  sb    HMMOOE}t K%'E 5zzT333#D$8$9$9:"Lr   c                     d S rf   r   r   s    r   r   zADSFactory.OverlapADS.read      Dr   c                 \   d | _         | j                            | j                   | j        |                                 z  |                                 z  | _        |                                 |                                 z  |                                 z  | _	        | j
        | _        d S rf   )r   rZ   rl   r   r8   r{   r}   r   ri   r   r   r   r   s    r   r   zADSFactory.OverlapADS._reinit  s    DKH##D$;<<<#'=#4466$7#0022$3D  &*%8%8%:%:#4466&7#0022&3D" .DIIIr   N)	r   r   r   r   r,   r   r   r   r   r   r   r   rb   r   d  si        	 		/ 	/ 	/	 	 	"	 	 	 	 	 			/ 		/ 		/ 		/ 		/r   rb   c                   $    e Zd ZdZd Zd Zd ZdS )ADSFactory.LimiterADSz
        A class for AudioDataSource objects that can read a fixed amount of data.
        This can be useful when reading data from the microphone or from large audio files.
        c                 |    t           j                            | |           || _        |                                  d S rf   )r   r   r,   r9   r   )r   rZ   r9   s      r   r,   zADSFactory.LimiterADS.__init__  s3    #,,T3777$DMLLNNNNNr   c                     | j         | j        k    rd S | j                                        }|d S | xj         t	          |          z  c_         | j         | j        k    r|                                  |S rf   )_total_read_bytes_max_read_bytesrZ   r   r.   rv   r   s     r   r   zADSFactory.LimiterADS.read  sn    %$*>>>tHMMOOE}t""c%jj0""%$*>>>

Lr   c                     t          | j        |                                 z            |                                 z  |                                 z  | _        d| _        d S r(   )r]   r9   r^   r{   r}   r   r   r   s    r   r   zADSFactory.LimiterADS._reinit  s]    #&t}8N8N8P8P'P#Q#Q"&"7"7"9"9$:"&"3"3"5"5$6D  &'D"""r   N)r   r   r   r   r,   r   r   r   r   r   r`   r     sK        	 	
	 	 		 	 		' 	' 	' 	' 	'r   r`   c                   B    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )ADSFactory.RecorderADSz
        A class for AudioDataSource objects that can record all audio data they read,
        with a rewind facility.
        c                 n    t           j                            | |           |                                  d S rf   )r   r   r,   r   r   s     r   r,   zADSFactory.RecorderADS.__init__  s,    #,,T3777LLNNNNNr   c                     d S rf   r   r   s    r   r   zADSFactory.RecorderADS.read  r   r   c                 p    | j                                         }|| j                            |           |S rf   )rZ   r   r   appendr   s     r   _read_and_recz$ADSFactory.RecorderADS._read_and_rec  s2    HMMOOE ""5)))Lr   c                 4    | j                                         S rf   )rZ   r   r   s    r   _read_simplez#ADSFactory.RecorderADS._read_simple  s    8==??"r   c                    | j         r|                     | j                  }t          ||                                 |                                 |                                           }|                     |           |                                  g | _        d| _         | j	        | _
        d S | j                                         |                                 s|                                  d S d S )NF)_record_concatenater   r	   r^   r{   r}   rr   rt   r   r   rZ   r   rx   )r   dbufferasources      r   r   zADSFactory.RecorderADS.rewind  s    |   ++DK88+GT5K5K5M5M-1-B-B-D-D-1->->-@-@B B
 %%g...		 $ -			 !!!||~~  IIKKKKK   r   c                     dS NTr   r   s    r   r   z$ADSFactory.RecorderADS.is_rewindable  s    4r   c                 :    d| _         g | _        | j        | _        d S r   )r   r   r   r   r   s    r   r   zADSFactory.RecorderADS._reinit  s    DLDK*DIIIr   c                 x    	 d                     |          S # t          $ r d                     |          cY S w xY w)Nr    )joinrS   r#   s     r   r   z#ADSFactory.RecorderADS._concatenate  sJ    % xx~~% % % %wwt}}$$$%s    99N)r   r   r   r   r,   r   r   r   r   r   r   r   r   r   r   ra   r     s        	 	
	 	 	
	 	 		 	 		# 	# 	#	  	  	 ,	 	 		+ 	+ 	+	% 	% 	% 	% 	%r   ra   N)r   r   r   r   staticmethodrV   rZ   r   r_   r   rb   r`   ra   r   r   r   r   r      sG        $ MX MX \MXj V V \Vr7; 7; 7; 7; 7;* 7; 7; 7;t% % % % % % % %PA/ A/ A/ A/ A/\ A/ A/ A/J' ' ' ' '\ ' ' 'DB% B% B% B% B%l B% B% B% B% B%r   r   c                       e Zd ZdZer7ej        ej        ej        dZ	e
d             Ze
d             Ze
d             Zn'ddddZ	e
d	             Ze
d
             Ze
d             ZddZd Zd Zd ZdS )r   a  
    The most basic auditok audio frame validator.
    This validator computes the log energy of an input audio frame
    and return True if the result is >= a given threshold, False 
    otherwise.
    
    :Parameters:
    
    `sample_width` : *(int)*
        Number of bytes of one audio sample. This is used to convert data from `basestring` or `Bytes` to
        an array of floats.
        
    `energy_threshold` : *(float)*
        A threshold used to check whether an input data buffer is valid.
    )r         c                     t          j        t          j        | t          j        |                   t           j                  S )N)dtype)numpyr   
frombufferr   _formatsfloat64signalr@   s     r   _convertzAudioEnergyValidator._convert&  sA    ;u/>R>[\h>ijjjrwr  A  A  A  Ar   c                 f    t          t          j        | |                     t          |           z  S rf   )floatr   dotr.   )r   s    r   _signal_energyz#AudioEnergyValidator._signal_energy*  s'    662233c&kkAAr   c                 t    t                               |           }|dk    rdS dt          j        |          z  S Nr   i8g      $@)r   r   r   log10r   energys     r   _signal_log_energyz'AudioEnergyValidator._signal_log_energy.  s8    )88@@F{{tV,,,,r   bhic                 ^    t          dt          t          j        |         |                     S )Nd)r   r   r   r   s     r   r   zAudioEnergyValidator._convert:  s&    e$8$A,$OQWXXYYYr   c                 D    d}| D ]
}|||z  z  }|t          |           z  S )Ng        )r.   )r   r   as      r   r   z#AudioEnergyValidator._signal_energy>  s6    F    !a%CKK''r   c                 t    t                               |           }|dk    rdS dt          j        |          z  S r   )r   r   mathr   r   s     r   r   z'AudioEnergyValidator._signal_log_energyE  s8    )88@@F{{tF++++r   -   c                 "    || _         || _        d S rf   )r@   _energy_threshold)r   r@   energy_thresholds      r   r,   zAudioEnergyValidator.__init__M  s    (!1r   c                     t                               || j                  }t                               |          | j        k    S )a  
        Check if data is valid. Audio data will be converted into an array (of
        signed values) of which the log energy is computed. Log energy is computed
        as follows:
        
        .. code:: python
        
            arr = AudioEnergyValidator._convert(signal, sample_width)
            energy = float(numpy.dot(arr, arr)) / len(arr)
            log_energy = 10. * numpy.log10(energy)
        
        
        :Parameters:
        
        `data` : either a *string* or a *Bytes* buffer
            `data` is converted into a numerical array using the `sample_width`
            given in the constructor.
        
        :Retruns:
        
        True if `log_energy` >= `energy_threshold`, False otherwise.
        )r   r   r@   r   r   )r   r$   r   s      r   r%   zAudioEnergyValidator.is_validR  s8    0 &..tT5FGG#66v>>$BXXXr   c                     | j         S rf   r   r   s    r   get_energy_thresholdz)AudioEnergyValidator.get_energy_thresholdm  s    %%r   c                     || _         d S rf   r   )r   	thresholds     r   set_energy_thresholdz)AudioEnergyValidator.set_energy_thresholdp  s    !*r   N)r   )r   r   r   r   _WITH_NUMPYr   int8int16int32r   r   r   r   r   r,   r%   r   r   r   r   r   r   r     s>        "  (,zu{u{CC		A 	A 
	A 
	B 	B 
	B 
	- 	- 
	- 	- ,,		Z 	Z 
	Z 
	( 	( 
	( 
	, 	, 
	,2 2 2 2
Y Y Y6& & &+ + + + +r   r   )r   abcr   r   r   r   ior   r   r	   r
   
exceptionsr   sysr   r   ImportErrorebuiltinsr   r1   version_info__all__r   r   r   r   r   r   r   r   <module>r      s   ( ( ' ' ' ' ' ' '        G G G G G G G G G G G G ) ) ) ) ) ) 



LLLKK   KKKKKKJJ   
6!!
 d
c
c              / / / / /z / / /fN
% N
% N
% N
% N
% N
% N
% N
%ba+ a+ a+ a+ a+= a+ a+ a+ a+ a+s*   3 A?AA A-A((A-