
    Sh                     8   d Z ddlZddlZddlmZmZ ddlmZ ddlZddl	Z	ddl
Z
ddlZddlZ	 ddlZddlmZmZ n'# e$ r ej        dk    r	ddlmZmZ nddlmZmZ Y nw xY w	 ddlmZ dZn# e$ r d	ZY nw xY wd
dlmZ d
dlmZmZmZmZ d
dlmZmZ ddlm Z! g Z"e!Z dZ#dZ$dZ%d
Z&dZ'dZ( G d de)          Z* G d de)          Z+d/dZ,d/dZ-g ddfdZ.d Z/ G d de          Z0 G d de0          Z1 G d de0          Z2 G d  d!e0          Z3 G d" d#e0          Z4 G d$ d%e0          Z5d/d&Z6e7d'k    re%rej8        9                    d(           e&rddl:Z: e:j;                     e'rddl<Z<ddl=Z=d)Z> e<j?        d*e>            e@d+d,          ZA e=jB        e>eA-          ZCeCD                                E                    d.          ZFeFG                                 eAH                                  ejI        d            ejI         e6                       dS dS )0a  
auditok.auditok -- Audio Activity Detection tool

auditok.auditok is a program that can be used for Audio/Acoustic activity detection.
It can read audio data from audio files as well as from built-in device(s) or standard input 


@author:     Mohamed El Amine SEHILI

@copyright:  2015 Mohamed El Amine SEHILI

@license:    GPL v3

@contact:    amine.sehili@gmail.com
@deffield    updated: 02 Dec 2015
    N)OptionParserOptionGroup)Thread)QueueEmpty)   r   )AudioSegmentTF   )StreamTokenizer)PyAudioSourceBufferAudioSourceStdinAudioSource
player_for)
ADSFactoryAudioEnergyValidator)__version__z
2015-11-23z
2015-12-02AUDITOK_LOGGERc                       e Zd ZdS )AudioFileFormatErrorN__name__
__module____qualname__     U/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/auditok/cmdline.pyr   r   ?           Dr   r   c                       e Zd ZdS )TimeFormatErrorNr   r   r   r   r   r   B   r   r   r   c                 	   |                                  }d}||                                 }|dk    s||                    d          r|                    dd           }||                    dd           }|                    dd           }||                    dd           }|                    dd           }||                    d	d           }d |||fv rt          d
          t	          |                                           }d}t          r|                    dd           }	|	|                    dd           }	|	d}	n!	 t          |	          }	n# t          $ r Y nw xY wt          |	t                    s%|	                                 dvrt          d          d }
|rt          ||||          }
|dv s|*|                    d          rt          j        |           }
n|dk    s|*|                    d          rt          j        |           }
nx|dk    s|*|                    d          rt          j        |           }
nF|dk    s|*|                    d          rt          j        |           }
nt          j        |           }
|
j        dk    rt          |	t                    rQ|	|
j        k    r(t          d                    |	|
j                            |
                                |	dz
           }
n|	                                 }|dk    r|
                    d          }
ne|	                                 dk    r|
                                d         }
n2|	                                 dk    r|
                                d         }
t)          |
j        |
j        |
j        |
j                  S |r'|dk    rt          d           t)          ||||          S |d!v s||                    d          rt1          j        |           }|                                }|dk    r#|                                 t          d           |                                }|                                }|                    |                                          }|                                 t)          ||||          S t?          d"          )#NFraw.rawsampling_ratesrsample_widthswchannelschz.All audio parameters are required for raw dataTuse_channelucr
   )leftrightmixz=channel must be an integer or one of 'left', 'right' or 'mix'r%   
frame_rater'   )wavewav.wavmp3z.mp3oggz.oggflvz.flvz;Can not use channel '{0}', audio file has only {1} channelsr-   r+   r   r,   )data_bufferr#   r%   r'   z/Cannot handle multi-channel audio without pydubr1   r0   zCannot read audio file format) lowerendswithpop	Exceptionopenread
WITH_PYDUBint
ValueError
isinstancer	   from_wavfrom_mp3from_oggfrom_flv	from_filer'   formatsplit_to_monoset_channelsr   _datar/   r%   r0   getnchannelsclosegetframerategetsampwidth
readframes
getnframesr   )filenamefiletypekwargslower_fnamerawdatasrateswidthr(   datar)   asegmentch_lowerwfps                r   file_to_audio_sourcer\   E   s   ..""KG>>##5X-+2F2Fv2N2N-

?D11=JJtT**END11>ZZd++FZZ
D)):D$''BFE2&&&LMMMH~~""$$  MDjj55 **T400KKK!+..    +-- 	^k6G6G6I6IMe6e6e\]]] 	^#Dv%Z\]]]Ho%%(*:{?S?STZ?[?[*:#,X66HH8#38L8LV8T8T#3#,X66HH8#38L8LV8T8T#3#,X66HH8#38L8LV8T8T#3#,X66HH#-h77Hq  +s++ ;!222$%b%i%ijuw  xI  &J  &J  K  K  K'5577aHHH&,,..u$$'44Q77HH &&((F22'5577:HH &&((G33'5577:H x~5=5H4<4I080AC C C 	C  	>Qww !RSSS$T5&"===&&8+;@T@TU[@\@\+;)H%%C!!##BQww		 !RSSS$$&&E%%''F>>#.."2"233DIIKKK$T5&"==="#BCCCs   	E 
E&%E&c                 &   |                                 }||                                 }|dk    s|P|                    d          r;t          |d          }|                    |            |                                 d S |                    dd           }||                    dd           }|                    dd           }||                    dd           }|                    dd           }||                    d	d           }d |||fv rt          d
          |dv s||                    d          rt          j        |d          }|                    |           |	                    |           |
                    |           |                    |            |                                 d S t          r,t          | |||          }	|	                    ||           d S t          d                    ||                    )Nr!   r"   wr#   r$   r%   r&   r'   r(   z5All audio parameters are required to save no raw datar7   r2   r.   rG   z-cannot write file format {0} (file name: {1}))r8   r9   r<   writerL   r:   r;   r0   setnchannelssetsampwidthsetframeratewriteframesr>   r	   exportr   rG   )
rX   rQ   rR   rS   rT   fprV   rW   r(   rY   s
             r   save_audio_datarg      s   ..""K>>## 5X-+2F2Fv2N2N-(C  




 JJ--E}

4&&ZZ--F~D$''	J	%	%B	zZZd##r"""OPPP?""x'7K<P<PQW<X<X'7Yx%%



t





	 o6eVXYYY22222 ##R#Y#YZbdl#m#mnnnr   c           
      "   dd l m} dd l}|                    d|                    t          t          |                               |z  d|z            }t          |          t          |           k    r'|d t          |           t          |          z
           }|D ] \  }	}
|                    |	|
dddd          }!|                    |d	d
dd          }|	                    ||            |
                    dgdd	d          }|                                                    |          }|                    dd           |                    dd           ||                    |d           |r|                                 d S d S )Nr                 ?gr   g?)	facecoloreclwalphar
   z--z(Energy threshold as normalized amplitude)yrp   lsclabelzDetection threshold)ri   gRQ?rj   g&1?   )bbox_to_anchorlocfontsizezTime (s)   )ry   zAmplitude (normalized)x   )dpi)matplotlib.pyplotpyplotnumpyarangeceilfloatlenaxvspanaxhlineplotlegendgca
add_artistxlabelylabelsavefigshow)signalr#   energy_as_amp
detectionsr   save_aspltnptstartendpliner   axs                  r   plot_allr      s   ######
		"bggeCKK0011MA2mCSUUA
1vvF$Fc!ff$$%  Q Q
sKKsc!CKPP;;1Dn;ooDHHQZZ./@TZ[fhZiiF			f	%	%BJJzBJ'''JJ'"J555G%%% 




 r   c                      dk    rd }n dk    rd }n                      dd                                 dd                                 d	d
                                 dd           	                      d          }t          d                     ||dz                                # t          $ r Y nw xY w fd}|S )z1
    Accepted format directives: %i %s %m %h
    %Sc                 ,    d                     |           S )N{:.2f}r_   secondss    r   
_fromatterz,seconds_to_str_fromatter.<locals>._fromatter  s    ??7+++r   z%Ic                 L    d                     t          | dz                      S )Nz{0}  )rG   r?   r   s    r   r   z,seconds_to_str_fromatter.<locals>._fromatter  s     <<GdN 3 3444r   z%hz	{hrs:02d}z%mz
{mins:02d}%sz
{secs:02d}z%iz{millis:03d}%z"Unknow time format directive '{0}'rm   c                     t          | dz            }t          |d          \  }}t          |d          \  }}t          |d          \  }}                    ||||          S )Nr   i6 i`  )hrsminssecsmillis)r?   divmodrG   )r   r   r   r   r   _formats        r   r   z,seconds_to_str_fromatter.<locals>._fromatter  sg    4((F 11KC!&%00LD&!&$//LD&>>c4>OOOr   )replaceindexr   rG   r@   )r   r   is   `  r   seconds_to_str_fromatterr      s    $	, 	, 	, 	, 
D	5 	5 	5 	5 //$44//$55//$55//$77	c""A!"F"M"MgVWXYZ[X[V[n"]"]^^^ 	 	 	D		P 	P 	P 	P 	P s   /AB1 1
B>=B>c                   4    e Zd Zd
dZd Zd Zd Zd Zd	 ZdS )Worker皙?FNc                    || _         || _        || _        | j        r| j        zt          j        t
                    | _        | j                            t          j                   t          j        t          j
                  }| j                            |           t                      | _        t                      | _        t          j        |            d S N)timeoutdebugloggerlogging	getLoggerLOGGER_NAMEsetLevelDEBUGStreamHandlersysstdout
addHandlerr   _inbox_stop_requestr   __init__)selfr   r   r   handlers        r   r   zWorker.__init__#  s    
: 	,$+-!+K88DKK  ///+CJ77GK""7+++gg"WWr   c                 :    | j                             |           d S r   )r   r   r   messages     r   debug_messagezWorker.debug_message3  s    '"""""r   c                 l    	 | j                                         }|dk    rdS d S # t          $ r Y dS w xY w)NstopTF)r   
get_nowaitr   r   s     r   _stop_requestedzWorker._stop_requested6  sW    	(3355G&  t !   	 	 	55	s   % 
33c                 b    | j                             d           |                                  d S )Nr   )r   putjoinr   s    r   r   zWorker.stop@  s*    v&&&		r   c                 :    | j                             |           d S r   )r   r   r   s     r   sendzWorker.sendD  s         r   c                 j    	 | j                             | j                  }|S # t          $ r Y d S w xY w)N)r   )r   getr   r   r   s     r   _get_messagezWorker._get_messageG  sE    	koodlo;;GN 	 	 	44	s   !$ 
22r   FN)	r   r   r   r   r   r   r   r   r   r   r   r   r   r   !  ss            # # #    ! ! !    r   r   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )TokenizerWorkerEND_OF_PROCESSINGc                     || _         || _        || _        || _        t	                      | _        d| _        t                              |            d S )Nr   )	ads	tokenizeranalysis_window	observersr   r   countr   r   )r   r   r   r   r   s        r   r   zTokenizerWorker.__init__S  sI    "."gg
r   c                       fd} j                                           j                             |            j        D ]!}|                    t          j                   "d S )Nc                     d                     |           }xj        dz  c_        |j        z  }|dz   j        z  }||z
  dz   j        z  }j        D ]$}|                    j        ||||||d           %d S )Nr   r
   )id
audio_datar   r   
start_timeend_timeduration)r   r   r   r   notify)	rX   r   r   r   r   r   r   observerr   s	           r   notify_observersz-TokenizerWorker.run.<locals>.notify_observers^  s    $JJJ!OJJ!55JA!55Hea4+??H !N " "
0:+0),0:.6.6!8 !8 " " " "" "r   )data_sourcecallback)r   r<   r   tokenizer   r   r   r   )r   r   r   s   `  r   runzTokenizerWorker.run\  s|    	" 	" 	" 	" 	"& 	D;KLLL 	? 	?HOOO=>>>>	? 	?r   c                 :    | j                             |           d S r   )r   appendr   r   s     r   add_observerzTokenizerWorker.add_observerv      h'''''r   c                 :    | j                             |           d S r   )r   remover   s     r   remove_observerzTokenizerWorker.remove_observery  r   r   c                 `    |                                  rd S | j                                        S r   )r   r   r=   r   s    r   r=   zTokenizerWorker.read|  s+    !! 	#48==??"r   N)	r   r   r   r   r   r   r   r   r=   r   r   r   r   r   O  se        +  ? ? ?4( ( (( ( (# # # # #r   r   c                   "    e Zd ZddZd Zd ZdS )PlayerWorkerr   FNc                 P    || _         t                              | |||           d S N)r   r   r   )playerr   r   )r   r   r   r   r   s        r   r   zPlayerWorker.__init__  s)    gU6JJJJJr   c           
      r   	 |                                  rd S |                                 }||t          j        k    rd S |                    dd           }|                    dd           }|                    dd           }|                    dd           }|                    dd           }|| j        re|                     d                    |d                    |          d                    |          d                    |          	                     | j        	                    |           7)
NTr   r   r   r   r   zC[PLAY]: Detection {id} played (start:{start}, end:{end}, dur:{dur}){:5.2f})r   r   r   dur)
r   r   r   r   r:   r   r   rG   r   play)r   r   r   r   r   r   _ids          r   r   zPlayerWorker.run  sB   	1##%% ''))G"o???E$[[t<<
$[[t<<
";;z488kk*d33kk$--)z x**+p+w+w{~'..z::	@P@PQY@Z@Z`i`p`pqt`u`u ,x ,w ,w x x xK$$Z000'	1r   c                 0    |                      |           d S r   r   r   s     r   r   zPlayerWorker.notify      		'r   r   r   r   r   r   r   r   r   r   r   r   r     sJ        K K K K1 1 1,    r   r   c                   "    e Zd ZddZd Zd ZdS )CommandLineWorkerr   FNc                 P    || _         t                              | |||           d S r   )commandr   r   )r   r
  r   r   r   s        r   r   zCommandLineWorker.__init__  s)    gU6JJJJJr   c                 0   	 |                                  rd S |                                 }||t          j        k    rd S |                    dd           }|                    dd           }|t          j        d          }|                    |           | j        	                    d|j
                  }| j        r*|                     d                    ||                     t          j        |           t          j        |j
                   )	NTr   r   F)delete$z%[CMD ]: Detection {id} command: {cmd})r   cmd)r   r   r   r   r:   tempfileNamedTemporaryFiler`   r
  r   namer   r   rG   ossystemunlink)r   r   r   r  raw_audio_filer  s         r   r   zCommandLineWorker.run  s   	3##%% ''))G"o???E$[[t<<
kk$--)%-%@%N%N%NN"((444,..sN4GHHCz l**+R+Y+Y]`fi+Y+j+jkkkIcNNNIn1222%	3r   c                 0    |                      |           d S r   r  r   s     r   r   zCommandLineWorker.notify  r  r   r   r  r   r   r   r  r    sJ        K K K K3 3 3*    r   r  c                   "    e Zd ZddZd Zd ZdS )TokenSaverWorkerr   FNc                 l    || _         || _        || _        t                              | |||           d S r   )name_formatrR   rS   r   r   )r   r  rR   r   r   r   rS   s          r   r   zTokenSaverWorker.__init__  s8    & gU6JJJJJr   c                    	 |                                  rd S |                                 }|U|t          j        k    rd S |                    dd           }|                    dd           }|                    dd           }|                    dd           }|t          |          dk    r| j                            |d                    |          d                    |                    }	 | j        r*| 	                    d	                    ||
                     t          ||fd| j        i| j         nF# t          $ r9}t          j                            t#          |          dz              Y d }~nd }~ww xY w)NTr   r   r   r   r   r   Nr   r   z'[SAVE]: Detection {id} saved as {fname})r   fnamerR   
)r   r   r   r   r:   r   r  rG   r   r   rg   rR   rS   r;   r   stderrr`   str)r   r   r   r   r   r  r  es           r   r   zTokenSaverWorker.run  s   	8##%% ''))G"o???E$[[t<<
$[[t<<
";;z488kk$--)c*oo.A.A ,33c8??S]C^C^fnfufuv~ff3  A  AE8: v ../X/_/_cfns/_/t/tuuu'
EaaDMaUYU`aaaa$ 8 8 8
((Q$777777778'	8s   2AD> >
F/E<<Fc                 0    |                      |           d S r   r  r   s     r   r   zTokenSaverWorker.notify  r  r   r   r  r   r   r   r  r    sJ        K K K K8 8 8.    r   r  c                   @    e Zd Zdd ed          dddfdZd Zd ZdS )		LogWorkerFz{start} {end}r   r   Nc                 z    || _         || _        || _        g | _        t                              | |||           d S r   )print_detectionsoutput_formattime_formatterr   r   r   )r   r'  r(  r)  r   r   r   s          r   r   zLogWorker.__init__  sC     !1*,gU6JJJJJr   c           	      T   	 |                                  rd S |                                 }|y|t          j        k    rd S |                    dd           }|                    dd           }|                    dd           }|                    dd           }|                    dd           }|                    dd           }|t          |          dk    r| j        rQ|                     d	                    |d
                    |          d
                    |                               | j	        rPt          | j                            ||                     |          |                     |                               | j                            |||||f           )NTr   r   r   r   r   r   r   z1[DET ]: Detection {id} (start:{start}, end:{end})r   )r   r   r   )r   r   r   r   r:   r   r   r   rG   r'  printr(  r)  r   r   )r   r   r   r  r   r   r   r   s           r   r   zLogWorker.run  s   	T##%% ''))G"o???E$[[t<<
kk$--GT22kk%..$[[t<<
";;z488)c*oo.A.Az =**+^+e+eil"+"2"2:">"> ) 0 0 : : ,f ,< ,< = = = , Bd077S$($7$7
$C$C"&"5"5h"?"? 8 A A B B B O**CZ+RSSS;	Tr   c                 0    |                      |           d S r   r  r   s     r   r   zLogWorker.notify  r  r   )r   r   r   r   r   r   r   r   r   r   r%  r%    si        (-_ 8 8 > >SXaeK K K KT T TB    r   r%  c           
         !"# t           j                            t          j        d                   }t
          }dt          z  }d|d|d}d}d}| t          j        d	d         } 	 t          |||
          }t          |d          }|	                    ddddd           |	                    ddddt          dd           |	                    ddddt          dd           |	                    dddd t          dd           |	                    d!d"d#d$t          dd%           |	                    d&d'd(d)t          dd%           |	                    d*d+d,d-t          d.d%           |                    |           t          |d/d0          }|	                    d1d2d3d4t          d5d           |	                    d6d7d8d9t          d:d           |	                    d;d<d=d>t          d?d           |	                    d@dAdBdCt          dDd           |	                    dEdFdGdHdIdJK           |	                    dLdMdNdOt          dPd           |                    |           t          |dQdR          }|	                    dSdTdUdVt          dWdX           |	                    dYdZd[d\t          d	dX           |	                    d]d^d_d`t          dadX           |                    |           t          |dbdc          }|	                    dddedfdgdt          d%h           |	                    didjdkdldIdJK           |	                    dmdndodpdIdJK           |	                    ddqdrdst          dd           |	                    ddtdudvt          dwd%           |	                    ddxdydzt          d{d%           |                    |           |	                    d|d}d~ddIdJK           |	                    dddddIdJK           |	                    ddddt          dd           |                    |           \  #}	#j        dk    r"t!          #j        #j        #j                  !n#j        "t)          #j        #j        #j                  !n	 t/          #j        #j        #j                  !nb# t0          $ rU t          j                            d           t          j                            d           t          j        da           Y nw xY wt9          j        t<                    }
|
                    t8          j                    t9          j!        t          j"                  }#j#        s#j$        s |                    t8          j%                   n|                    t8          j                    |
&                    |           #j'        |
                    t8          j                    d#_$        t9          j(        #j'        d          }t9          j)        d          }|*                    |           |                    t8          j                    |
&                    |           #j+        dup#j,        p#j-        du}t]          j/        !#j0        #j1        |           te          !3                                #j4                  }#j5        rtl          j7        }nd}d#j0        z  }tm          |#j8        |z  t          #j9        |z            #j:        |z  |          }g }d}#j;        (	 #j;        <                    ddd          }#j=        }|2t           j        >                    #j;                  d	         d	d         }|dk    rd}t          #j;        |#j$        |
!@                                !3                                !A                                          }|B                    |           n[# t0          $ rN t          j                            d<                    #j;                             t          j        da           Y nw xY w#jC        r	 t          !          }t          |#j$        |
          }|B                    |           nb# t0          $ rU t          j                            d           t          j                            d           t          j        da           Y nw xY w#jF        It          #jF                  dk    r1t          #jF        #j$        |
          }|B                    |           #j#        r#j,        #j-        #jI        J                    dd          J                    dd          J                    dd          }t          #jL                  }t          #j#         |||
#j$                  "|B                    "           t           |#j0        |          } !#fd} !"#fd}|D ]}|O                                 |O                                 	 t          jQ        d	           t          t          jS                              d	k    rn:d}#j+        
 |             #j,        s#j-        
 |             dS # t          $ r\ ||U                                 |D ]}|U                                 #j+        
 |             #j,        s#j-        
 |             Y dS t0          $ r_}t          j                            |dz   t          |          z   dz              t          j                            d           Y d}~daS d}~ww xY w)zCommand line options.r   r   z%prog z () zCopyright 2015 Mohamed El Amine SEHILI                                                            Licensed under the General Public License (GPL) Version 3 
http://www.gnu.org/licenses/Nr
   )versionepilogdescriptionz[Input-Output options]z-iz--inputinputzXInput audio or video file. Use - for stdin [default: read from microphone using pyaudio]FILE)desthelpmetavarz-tz--input-type
input_typezRInput audio file type. Mandatory if file name has no extension [default: %default]String)r5  r6  typedefaultr7  z-Mz
--max_timemax_timez_Max data (in seconds) to read from microphone/file [default: read until the end of file/stream]FLOATz-Oz--output-mainoutput_mainzPSave main stream as. If omitted main stream will not be saved [default: omitted]z-oz--output-tokensoutput_tokenszOutput file name format for detections. Use {N} and {start} and {end} to build file names, example: 'Det_{N}_{start}-{end}.wav'STRINGz-Tz--output-typeoutput_typez}Audio type used to save detections and/or main stream. If not supplied will: (1). guess from extension or (2). use wav formatz-uz--use-channelr)   zChoose channel to use from a multi-channel audio file (requires pydub). 'left', 'right' and 'mix' are accepted values. [Default: 1 (i.e. 1st or left channel)]1z[Tokenization options]z+Set tokenizer options and energy threshold.z-az--analysis-windowr   z=Size of analysis window in seconds [default: %default (10ms)]g{Gz?z-nz--min-durationmin_durationzBMin duration of a valid audio event in seconds [default: %default]r   z-mz--max-durationmax_durationzBMax duration of a valid audio event in seconds [default: %default]   z-sz--max-silencemax_silencez_Max duration of a consecutive silence within a valid audio event in seconds [default: %default]g333333?z-dz--drop-trailing-silencedrop_trailing_silencezGDrop trailing silence from a detection [default: keep trailing silence]
store_trueF)r5  r6  actionr;  z-ez--energy-thresholdenergy_thresholdz6Log energy threshold for detection [default: %default]2   z[Audio parameters]zDefine audio parameters if data is read from a headerless file (raw or stdin) or you want to use different microphone parameters.z-rz--rater#   z/Sampling rate of audio data [default: %default]i>  INTz-cz
--channelsr'   z4Number of channels of audio data [default: %default]z-wz--widthr%   z4Number of bytes per audio sample [default: %default]rm   z[Do something with detections]z4Use these options to print, play or plot detections.z-Cz	--commandr
  z|Command to call when an audio detection occurs. Use $ to represent the file name to use with the command (e.g. -C 'du -h $'))r5  r6  r;  r:  r7  z-Ez--echoechozIPlay back each detection immediately using pyaudio [default: do not play]z-pz--plotr   z?Plot and show audio signal and detections (requires matplotlib)z--save-image
save_imagezYSave plotted audio signal and detections as a picture or a PDF file (requires matplotlib)z--printfprintfzprint detections one per line using a user supplied format (e.g. '[{id}]: {start} -- {end}'). Available keywords {id}, {start} and {end}z{id} {start} {end}z--time-formattime_formata  format used to print {start} and {end}. [Default= %default]. %S: absolute time in sec. %I: absolute time in ms. If at least one of (%h, %m, %s, %i) is used, convert time into hours, minutes, seconds and millis (e.g. %h:%m:%s.%i). Only required fields are printedr   z-qz--quietquietzhDo not print any information about detections [default: print 'id', 'start' and 'end' of each detection]z-Dz--debugr   z%Print processing operations to STDOUTz--debug-file
debug_filez#Print processing operations to FILE-)r#   r%   r'   )rQ   rR   r*   z$Cannot read data from audio device!
z:You should either install pyaudio or read data from STDIN
Tr^   z[%(asctime)s] | %(message)s)audio_source	block_durr<  record)r%   rJ  rj   )	validator
min_length
max_lengthmax_continuous_silencemoder  r1   )r  rR   r   r   r$   r&   r(   z-Wrong format for detections file name: '{0}'
)r   r   r   zCannot get an audio player!
zPYou should either install pyaudio or supply a command (-C option) to play audio
)r
  r   r   z\nr  z\t	z\r)r'  r(  r)  r   r   c            	         j         } | 2t          j                            j                  d         dd          } | dk    rd}                                                                                                                                   }t          |          dk    rRt          |j        |                                                                                                            d S d S )Nr
   r/  r1   r   )rX   rQ   rR   r$   r&   r(   )rA  r  pathsplitextr>  rL   rewindget_audio_sourceget_data_bufferr   rg   get_sampling_rateget_sample_widthget_channels)	main_typerX   r   asourceoptss     r   _save_main_streamzmain.<locals>._save_main_stream  s    )I G,,T-=>>qA!""E	B!	IIKKKJJLLL''))99;;D4yy1}}TD4Dy]d]v]v]x]x%,%=%=%?%?%,%9%9%;%;= = = = = = }r   c                  V   dd l }                                                                                                                                   }t          j        |                                          }d j        D             }d                                dz  dz
  z  dz
  }| 	                    | 
                    	j        |                     d          z  dz                      |z  }t          ||z                                  ||	j        	j                   d S )Nr   c                 .    g | ]}|d          |d         fS )r      r   ).0dets     r   
<listcomp>z'main.<locals>._plot.<locals>.<listcomp>  s%    MMM3q6CF+MMMr   rm      r
   
   )r   r   )r   rL   ra  rb  rc  r   _convertre  r   sqrtexprJ  logr   rd  r   rN  )
r   rX   r   r   max_amplituder   r   rh  
log_workerri  s
         r   _plotzmain.<locals>._plot  s/   IIKKKJJLLL''))99;;D)249Q9Q9S9STTFMMz7LMMMJ 8 8 : :Q > BCaGMGGBFF4+@266"::+MPR+R$S$STTWddMVm+W-F-F-H-H-Yclplu  BF  BQ  R  R  R  R  R  Rr   z: zfor help use -h
)Vr  r_  basenamer   argvr0  __updated__r   r   
add_optionr!  r   add_option_groupr?   
parse_argsr3  r   r#   r%   r'   r\   r8  r)   r   r;   r   r`   exitr   r   r   r   r   r   r   rQ  r   CRITICALr   rR  FileHandler	FormattersetFormatterr>  r   rN  r   r   r   r<  r   re  rJ  rG  r   DROP_TRAILING_SILENCErC  rD  rF  r?  rG   rA  r`  r  rd  rf  r   rM  r   r   r
  r   r  rO  r   r   rP  r%  r   r   timesleep	threading	enumerateKeyboardInterruptr   )$r{  program_nameprogram_versionprogram_build_dateprogram_version_stringprogram_longdescprogram_licenseparsergroupargsr   r   fmtrV  rW  r[  analysis_window_per_secondr   r   tokenizer_workerr  tok_typetoken_saverr   player_worker
cmd_workeroformat	converterrj  ry  obsr"  r   rh  rx  ri  s$                                   @@@@r   mainr    s    7##CHQK00LO+1@BTBTBTUjO |x|]&<EUcrsssF$<==yw  >X  bh  	i  	i  	i~L  H\  cf  pt  ~F  	G  	G  	G|*  De  lq  {  IP  	Q  	Q  	Q]  J\  cf  pt  ~D  	E  	E  	E0  NO  VY  cg  qy  	z  	z  	z]  JI  PS  ]a  ks  	t  	t  	t]  Jj  qt  ~A  KS  	T  	T  	T&&& F$<>kll29J  RQ  X]  gk  u|  	}  	}  	}/n  LP  W\  fi  sz  	{  	{  	{/n  LP  W\  fg  qx  	y  	y  	y]  Jk  rw  AD  NU  	V  	V  	V8?V  ^g  q}  GL  	M  	M  	M3:L  TL  SX  bd  nu  	v  	v  	v&&& F$8  ;~    xoDu|  JO  Y^  	_  	_  	_|*Cy  AD  NO  Y^  	_  	_  	_y~Dz  BE  OP  Z_  	`  	`  	`&&&F$DF|}}{  B@  JN  UX  bj  	k  	k  	kxf  <G  Q]  gl  	m  	m  	mxf;|  GS  ]b  	c  	c  	c^,  Fa  il  vz  DJ  	K  	K  	KZh  >H  PS  ]q  {C  	D  	D  	D_=  HP  X[  ei  s{  	|  	|  	|&&&$	  ?i  s  IN  	O  	O  	O$	>eo{  FK  	L  	L  	L"n<Fksv  AE  OU  	V  	V  	V
 ((..t:&t7I6:6G26-A A AGG Z#*DJ]a]mnnnGG'8J7;7H37=B B B    
  !HIII
  !^___
 ";//&&&'
33: 	,TZ 	,W-....W]+++'"""?&OOGM***DJ)$/3??G#$ABBC  %%%W]+++g&&&!-YYdoUY>YnGAUbfbo  {A  B  B  B(g6N6N6P6Pcgcxyyy	 % 	"8DDD%'$*>%>"#iDDUXrDr/243DGa3a/b/b;?;KNh;h+/1 1 1	 	)+22QaQ2GG !,#!w//0BCCAFqrrJHr>>$H.4;MX`59ZSZSlSlSnSn292J2J2L2L292F2F2H2HJ J J   ----   
  !Q!X!XY]Yk!l!lmmm 9 	#G,, ,F$*U[ \ \ \  ////   
  !@AAA
  !tuuu
 <#DL(9(9A(=(=*4<tzZ`aaaJZ(((z 	)TY2do6Qk))%66>>udKKSSTY[_``G01ABBI"$*nT[2;FRVR\^ ^ ^JZ(((*3	4;OQZ[[	= 	= 	= 	= 	= 	= 	=		R 		R 		R 		R 		R 		R 		R 		R  	 	CIIKKKK   	JqMMM9&(())Q..	
  '9 	3EGGGq   '!!### 	 	CHHJJJJ'9 	3EGGGqq   
,s1vv5<===
,---qqqqq	s   )P+j6 !R7 6j6 7ATj6 TH'j6 >C`
 	j6 
Aa"j6 !a""
j6 -;b) (j6 )Adj6 dF,j6 6A"n	n$Am>>n__main__z-hzauditok.auditok_profile.txtzmain()zprofile_stats.txtwb)stream
cumulativer   )J__doc__r   r  optparser   r   r  r   r  r0   r  r   futurequeuer   r   ImportErrorversion_infopydubr	   r>   corer   ior   r   r   r   utilr   r   auditokr   r0  __all____date__r|  r   TESTRUNPROFILEr   r;   r   r   r\   rg   r   r   r   r   r   r  r  r%  r  r   r{  r   doctesttestmodcProfilepstatsprofile_filenamer   r<   	statsfileStatsr   
strip_dirs
sort_statsstatsprint_statsrL   r  r   r   r   <module>r     s   " 


 				 . . . . . . . .              'MMM""""""""" ' ' '
6!!&&&&&&&&&&&&&&&&&	'""""""JJ   JJJ " ! ! ! ! ! N N N N N N N N N N N N 2 2 2 2 2 2 2 2 * * * * * *
	

	 	 	 	 	9 	 	 		 	 	 	 	i 	 	 	jD jD jD jDZ-o -o -o -o` ?AtUY    4! ! !J+ + + + +V + + +\1# 1# 1# 1# 1#f 1# 1# 1#h    6   @       >         v      F- - - - - - - -bl l l l\ z   
8X/000D,d33	FL))<<<)),77CHTTVV# s!   ; !AA#A, ,A65A6