
    If                        d 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Zddl	m
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 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 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 G d# d$e      Z G d% d&e      Z G d' d(e      Zy#  ddlZY xY w))zPython API to Speech Dispatcher

Basic Python client API to Speech Dispatcher is provided by the 'SSIPClient'
class.  This interface maps directly to available SSIP commands and logic.

A more convenient interface is provided by the 'Speaker' class.

    N   )pathsc                   2    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ	y)	CallbackTypez5Constants describing the available types of callbacksindex_marksbeginendcancelpauseresumeN)
__name__
__module____qualname____doc__
INDEX_MARKBEGINENDCANCELPAUSERESUME     0/usr/lib/python3/dist-packages/speechd/client.pyr   r   $   sE    ?J E&
C;F E4F)r   r   c                       e Zd ZdZy)	SSIPErrorz;Common base class for exceptions during SSIP communication.Nr   r   r   r   r   r   r   r   r   ;   s    Er   r   c                   F     e Zd ZdZdZd	 fd	Zd Zd Zd Zd Z	d Z
 xZS )
SSIPCommunicationErrorz?Exception raised when trying to operate on a closed connection.Nc                 H    || _         || _        t        t        |   di | y )Nr   )_original_exception_descriptionsuperr   __init__)selfdescriptionoriginal_exceptionkwargs	__class__s       r   r#   zSSIPCommunicationError.__init__C   s%    #5 'i'1&1r   c                     | j                   S )zReturn the original exception if any

        If this exception is secondary, being caused by a lower
        level exception, return this original exception, otherwise
        None)r    r$   s    r   r&   z)SSIPCommunicationError.original_exceptionH   s     '''r   c                     || _         y)zXSet an additional exception
        
        See method additional_exception().
        N_additional_exception)r$   	exceptions     r   set_additional_exceptionz/SSIPCommunicationError.set_additional_exceptionP   s    
 &/"r   c                     | j                   S )zReturn an additional exception
        
        Additional exceptions araise from failed attempts to resolve
        the former problemr,   r*   s    r   additional_exceptionz+SSIPCommunicationError.additional_exceptionW   s    
 )))r   c                     | j                   S )zReturn error description)r!   r*   s    r   r%   z"SSIPCommunicationError.description^   s       r   c                 b   g }| j                         r|j                  | j                                | j                  r+|j                  dt        | j                               z          | j                  r+|j                  dt        | j	                               z          dj                  |      S )NzOriginal error: zAdditional error: 
)r%   appendr&   strr1   join)r$   msgss     r   __str__zSSIPCommunicationError.__str__b   s    KK((*+""KK*S1H1H1J-KKL$$KK,s43L3L3N/OOPyyr   NN)r   r   r   r   r-   r#   r&   r/   r1   r%   r9   __classcell__r(   s   @r   r   r   >   s*    I 2
(/*!r   r   c                       e Zd Zd Zd Zd Zy)SSIPResponseErrorc                 d    t         j                  | |d|       || _        || _        || _        y )Nz: )	Exceptionr#   _code_msg_datar$   codemsgdatas       r   r#   zSSIPResponseError.__init__m   s,    4T3!78
	
r   c                     | j                   S )z8Return the server response error code as integer number.)rA   r*   s    r   rE   zSSIPResponseError.codes       zzr   c                     | j                   S )z/Return server response error message as string.)rB   r*   s    r   rF   zSSIPResponseError.msgw   s    yyr   N)r   r   r   r#   rE   rF   r   r   r   r>   r>   l   s    r   r>   c                       e Zd ZdZd Zy)SSIPCommandErrorz9Exception raised on error response after sending command.c                     | j                   S )z7Return the command string which resulted in this error.rC   r*   s    r   commandzSSIPCommandError.command   rI   r   N)r   r   r   r   rO   r   r   r   rL   rL   |   s
    Cr   rL   c                       e Zd ZdZd Zy)SSIPDataErrorz6Exception raised on error response after sending data.c                     | j                   S )z-Return the data which resulted in this error.rN   r*   s    r   rG   zSSIPDataError.data   rI   r   N)r   r   r   r   rG   r   r   r   rQ   rQ      s
    @r   rQ   c                       e Zd ZdZy)
SpawnErrorz&Indicates failure in server autospawn.Nr   r   r   r   rT   rT      s    0r   rT   c                       e Zd ZdZdZ	 dZy)CommunicationMethodzBConstants describing the possible methods of connection to server.unix_socketinet_socketNr   r   r   r   UNIX_SOCKETINET_SOCKETr   r   r   rV   rV      s    LK;K9r   rV   c                      e Zd ZdZdZdZdZeez   ez   Zeez   ez   Zeez   Z	eez   Z
ej                  ej                  ej                  ej                  ej                   ej"                  dZd Zd Zd Zd	 Zd
 Zd Zd Zd Zd Zy)_SSIP_Connectionz/Implementation of low level SSIP communication.s   
   .s   ..)i  i  i  i  i  i  c                    |t         j                  k(  rt        j                  }|}nL|t         j                  k(  r.|r|sJ t        j
                  }t        j                  |      |f}nt        d      	 t        j                  |t        j                        | _	        | j                  j                  |       d| _        g | _        d| _        t!        j"                  d      | _        t!        j&                  | j(                  i dd	      | _        | j*                  j-                          y# t        j                  $ r}t        d|z   |      d}~ww xY w)
zInit connection: open the socket to server,
        initialize buffers, launch a communication handling
        thread.
        z Unsupported communication methodzCan't open socket using method )r&   Nr   r   z SSIP client communication threadT)targetr'   namedaemon)rV   rZ   socketAF_UNIXr[   AF_INETgethostbyname
ValueErrorSOCK_STREAM_socketconnecterrorr   _buffer_com_buffer	_callback	threading	Semaphore_ssip_reply_semaphoreThread_communication_communication_threadstart)r$   communication_methodsocket_pathhostportsocket_familysocket_connect_argsexs           r   r#   z_SSIP_Connection.__init__   s2     #6#B#BB"NNM"-!%8%D%DDD ="NNM#)#7#7#=t"D?@@	B!==8J8JKDLLL  !45 %.%8%8%;"  (;(;B&H(,. 	" 	""((* || 	B()J+?*@>@B B	Bs   4AD* *E=EEc                     	 | j                   j                  t        j                         | j                   j                          | j                  j                          y# t        j                  $ r Y Jw xY w)z>Close the server connection, destroy the communication thread.N)ri   shutdownrc   	SHUT_RDWRrk   closert   r7   r*   s    r   r   z_SSIP_Connection.close   s[    	LL!!&"2"23 	""'')	 || 		s   )A   A65A6c                    	 	 | j                         \  }}}dz  dk7  r9| j                  j                  |f       | j                  j                          W| j                  W| j                  |   }|t        j                  k(  rdd   i}ni }t        t        dd       \  }} | j                  |||fi | # t        $ r t        j                          Y w xY w)a*  Handle incoming socket communication.

        Listens for all incoming communication on the socket, dispatches
        events and puts all other replies into self._com_buffer list in the
        already parsed form as (code, msg, data).  Each time a new item is
        appended to the _com_buffer list, the corresponding semaphore
        'self._ssip_reply_semaphore' is incremented.

        This method is designed to run in a separate thread.  The thread can be
        interrupted by closing the socket on which it is listening for
        reading.d      N
index_mark   )_recv_messageIOErrorsysexitrm   r5   rq   releasern   _CALLBACK_TYPE_MAPr   r   mapint)r$   rE   rF   rG   typer'   msg_id	client_ids           r   rs   z_SSIP_Connection._communication   s     "&"4"4"6c4 SyA~  ''sD(9:**224~~)..t4<222*DG4FF$'T"1X$6!	vy$A&A)   
s   B< <CCc                    | j                   j                  | j                        }|dk(  rp	 | j                  j	                  d      }t        |      dk(  rt
        | xj                   |z  c_         | j                   j                  | j                        }|dk(  rp| j                   d| }| j                   |t        | j                        z   d | _         |j                  d      S #  t
        xY w)zuRead one whole line from the socket.

        Blocks until the line delimiter ('_NEWLINE') is read.
        
        i   r   Nutf-8)rl   find_NEWLINEri   recvr   lendecode)r$   pointerdlines       r   	_readlinez_SSIP_Connection._readline   s     ,,##DMM2mLL%%d+ 1v{LLALll''6G m ||HW%||GC,>$>$?@{{7##s   C% %C-c                    g }d}	 | j                         }t        |      dk\  sJ d       |dd |d   |dd }}}|j                         r|||k(  r|dv sJ d       |dk(  r|}t        |      |t	        |      fS |}|j                  |       )zTRead server response or a callback
        and return the triplet (code, msg, data).N   z$Malformed data received from server!   )- r   )r   r   isalnumr   tupler5   )r$   rG   cr   rE   septextrF   s           r   r   z_SSIP_Connection._recv_message  s     >>#Dt9>I#II>"2AhQabt#D<<>qyDAI*$M&LM %cz4y#uT{22AKK r   c                     | j                   j                         st        | j                  j	                          | j
                  d   }| j
                  d= |S )zdRead server response from the communication thread
        and return the triplet (code, msg, data).r   )rt   is_aliver   rq   acquirerm   )r$   responses     r   _recv_responsez_SSIP_Connection._recv_response!  sQ    
 ))224((""**,##A&Qr   c           	         	 |dv r:|d   t         j                  t         j                  fv st        |d   t              sJ dj                  |ft        t        t        |            z         }	 | j                  j                  |j                  d      | j                  z          | j!                         \  }}}|dz  dk7  rt#        |||      |||fS # t        j                  $ r t        d      w xY w)a  Send SSIP command with given arguments and read server response.

        Arguments can be of any data type -- they are all stringified before
        being sent to the server.

        Returns a triplet (code, msg, data), where 'code' is a numeric SSIP
        response code as an integer, 'msg' is an SSIP rsponse message as string
        and 'data' is a tuple of strings (all lines of response data) when a
        response contains some data.
        
        'SSIPCommandError' is raised in case of non 2xx return code.  See SSIP
        documentation for more information about server responses and codes.

        'IOError' is raised when the socket was closed by the remote side.
        
        )SETr   STOPr   r   r   "Speech Dispatcher connection lost.r   r   )ScopeSELFALL
isinstancer   r7   r   r   r6   ri   sendencoder   rc   rk   r   r   rL   )r$   rO   argscmdrE   rF   rG   s          r   send_commandz_SSIP_Connection.send_command.  s    " 44Aw5::uyy"99$T!Wc23 3hhzE#c4.$99:	OLLcjj1DMMAB --/c49>"4c22S$ || 	O()MNN	Os   -7C C1c                    |j                  d      }|j                  | j                        r't        | j                        }| j                  ||d z   }|j                  | j                  | j                        }	 | j                  j                  || j                  z          | j                         \  }}}|dz  dk7  rt        |||      |||fS # t        j                  $ r t        d      w xY w)ap  Send multiline data and read server response.

        Returned value is the same as for 'send_command()' method.

        'SSIPDataError' is raised in case of non 2xx return code. See SSIP
        documentation for more information about server responses and codes.
        
        'IOError' is raised when the socket was closed by the remote side.
        
        r   Nr   r   r   )r   
startswith_END_OF_DATA_MARKERr   _END_OF_DATA_MARKER_ESCAPEDreplace_RAW_DOTLINE_ESCAPED_DOTLINEri   r   _END_OF_DATArc   rk   r   r   rQ   )r$   rG   lrE   rF   response_datas         r   	send_dataz_SSIP_Connection.send_dataM  s     {{7# ??4334D,,-A33d12h>D ||D--t/D/DE	OLLdT%6%667 $(#6#6#8 c=9>c400S-'' || 	O()MNN	Os   ;(C C0c                     || _         y)a~  Register a callback function for handling asynchronous events.

        Arguments:
          callback -- a callable object (function) which will be called to
            handle asynchronous events (arguments described below).  Passing
            `None' results in removing the callback function and ignoring
            events.  Just one callback may be registered.  Attempts to register
            a second callback will result in the former callback being
            replaced.

        The callback function must accept three positional arguments
        ('message_id', 'client_id', 'event_type') and an optional keyword
        argument 'index_mark' (when INDEX_MARK events are turned on).

        Note, that setting the callback function doesn't turn the events on.
        The user is responsible to turn them on by sending the appropriate `SET
        NOTIFICATION' command.

        N)rn   )r$   callbacks     r   set_callbackz_SSIP_Connection.set_callbackn  s    ( "r   N)r   r   r   r   r   r   r   r   _END_OF_DATA_ESCAPEDr   r   r   r   r   r   r   r   r   r   r#   r   rs   r   r   r   r   r   r   r   r   r   r]   r]      s    9H"'11H<L#&AAHL11L"==+66+11+//+22+11+22 +D
*!BH$(">(B"r   r]   c                   "    e Zd ZdZd Zd Zd Zy)_CallbackHandlerz(Internal object which handles callbacks.c                 R    || _         i | _        t        j                         | _        y N)
_client_id
_callbacksro   Lock_lock)r$   r   s     r   r#   z_CallbackHandler.__init__  s    #^^%
r   c                    || j                   k7  ry | j                  j                          	 	 | j                  |   \  }}|||v r	 ||fi | |t        j
                  t        j                  fv r| j                  |= 	 | j                  j                          y # t        $ r Y &w xY w# | j                  j                          w xY wr   )	r   r   r   r   r   r   r   KeyErrorr   )r$   r   r   r   r'   r   event_typess          r   __call__z_CallbackHandler.__call__  s    '

	!0(,(?%+ &$+*=T,V,L,,l.A.ABB/JJ    JJ s(   B ?B( 	B%"B( $B%%B( (Cc                     | j                   j                          	 ||f| j                  |<   | j                   j                          y # | j                   j                          w xY wr   )r   r   r   r   )r$   r   r   r   s       r   add_callbackz_CallbackHandler.add_callback  sK    

	!'/&=DOOF#JJ DJJ s   A A$N)r   r   r   r   r#   r   r   r   r   r   r   r     s    2&
!$!r   r   c                       e Zd ZdZdZ	 dZy)r   zAn enumeration of valid SSIP command scopes.

    The constants of this class should be used to specify the 'scope' argument
    for the 'Client' methods.

    r$   allN)r   r   r   r   r   r   r   r   r   r   r     s     DL
CKr   r   c                   $    e Zd ZdZdZdZdZdZdZy)Prioritya  An enumeration of valid SSIP message priorities.

    The constants of this class should be used to specify the 'priority'
    argument for the 'Client' methods.  For more information about message
    priorities and their interaction, see the SSIP documentation.
    
    	importantr   messagenotificationprogressN)	r   r   r   r   	IMPORTANTTEXTMESSAGENOTIFICATIONPROGRESSr   r   r   r   r     s"     IDG!LHr   r   c                   &    e Zd ZdZdZ	 dZ	 dZ	 dZy)PunctuationModezkConstants for selecting a punctuation mode.

    The mode determines which characters should be read.

    r   nonesomemostN)r   r   r   r   r   NONESOMEMOSTr   r   r   r   r     s+    
 C*D6DHDr   r   c                       e Zd ZdZdZ	 dZy)DataModezWConstants specifying the type of data contained within messages
    to be spoken.

    r   ssmlN)r   r   r   r   r   SSMLr   r   r   r   r     s     DD:r   r   c                      e Zd ZdZdZ	 dZ	 dZ	 	 	 	 d/dZd Zd Z	d	 Z
d
 Zd Zd Zd Zd0dZd Zd Zd Zej(                  fdZej(                  fdZej(                  fdZej(                  fdZd Zd0dZej(                  fdZd Zej(                  fdZd Zej(                  fdZd Z ej(                  fdZ!ej(                  fdZ"d  Z#ej(                  fd!Z$d" Z%ej(                  fd#Z&d$ Z'ej(                  fd%Z(ej(                  fd&Z)ej(                  fd'Z*ej(                  fd(Z+ej(                  fd)Z,d* Z-d+ Z.d, Z/d- Z0d. Z1y)1
SSIPClientaL  Basic Speech Dispatcher client interface.

    This class provides a Python interface to Speech Dispatcher functionality
    over an SSIP connection.  The API maps directly to available SSIP commands.
    Each connection to Speech Dispatcher is represented by one instance of this
    class.
    
    Many commands take the 'scope' argument, thus it is shortly documented
    here.  It is either one of 'Scope' constants or a number of connection.  By
    specifying the connection number, you are applying the command to a
    particular connection.  This feature is only meant to be used by Speech
    Dispatcher control application, however.  More datails can be found in
    Speech Dispatcher documentation.

    Here is a simple example:

    from speechd import client
    c = client.SSIPClient("mytest")
    c.speak("hello, world!")
    z	127.0.0.1i  zspeech-dispatcher/speechd.sockNc
           
         t         j                  j                  d      }
t         j                  j	                  dt         j                  j	                  dt         j                  j                  |
d                  }t         j                  j                  || j                        }t        j                  || j                  | j                  d}|xs t         j                  j	                  d      }|r!|j                  | j                  |             nt         j                  j	                  d      }	 t        t         j                  j	                  d            }t         j                  j	                  d
      }|r||d<   |r||d<   n|r||d<   |	r|	|d<   n|r||d<   | j                  ||       | j                  |||       y	#  d	}Y pxY w)a[  Initialize the instance and connect to the server.

        Arguments:
          name -- client identification string
          component -- connection identification string.  When one client opens
            multiple connections, this can be used to identify each of them.
          user -- user identification string (user name).  When multi-user
            access is expected, this can be used to identify their connections.
          address -- server address as specified in Speech Dispatcher
            documentation (e.g. "unix:/run/user/joe/speech-dispatcher/speechd.sock"
            or "inet:192.168.0.85:6561")
          autospawn -- a flag to specify whether the library should
            try to start the server if it determines its not already
            running or not

        Deprecated arguments:
          method -- communication method to use, one of the constants defined in class
            CommunicationMethod
          socket_path -- for CommunicationMethod.UNIX_SOCKET, socket
            path in filesystem. By default, this is $XDG_RUNTIME_DIR/speech-dispatcher/speechd.sock
            where $XDG_RUNTIME_DIR is determined using the XDG Base Directory
            Specification.
          host -- for CommunicationMethod.INET_SOCKET, server hostname
            or IP address as a string.  If None, the default value is
            taken from SPEECHD_HOST environment variable (if it
            exists) or from the DEFAULT_HOST attribute of this class.
          port -- for CommunicationMethod.INET_SOCKET method, server
            port as number or None.  If None, the default value is
            taken from SPEECHD_PORT environment variable (if it
            exists) or from the DEFAULT_PORT attribute of this class.
         
        For more information on client identification strings see Speech
        Dispatcher documentation.
        ~XDG_RUNTIME_DIRXDG_CACHE_HOMEz.cache)rv   rw   rx   ry   SPEECHD_ADDRESSSPEECHD_HOSTSPEECHD_PORTNSPEECHD_SOCKETmethodry   rw   )ospath
expanduserenvirongetr7   DEFAULT_SOCKET_PATHrV   rZ   DEFAULT_HOSTDEFAULT_PORTupdate"_connection_arguments_from_addressr   _connect_with_autospawn_initialize_connection)r$   ra   	componentuseraddress	autospawnrx   ry   r   rw   _home_runtime_dir
_sock_pathconnection_args_addressenv_speechd_hostenv_speechd_portenv_speechd_socket_paths                     r   r#   zSSIPClient.__init__  s   N ""3'zz~~&7HXZ\ZaZaZfZfglnvZw9xyWW\\,0H0HI
3F3R3R*4#'#4#4#'#4#4 ?bjjnn->?""4#J#J8#TU
  "zz~~n=(#&rzz~~n'E#F  ')jjnn5E&F# ,2)*.'!*:'1<.(1H.$$_i@##D$	:#(#' s   5(G Gc                     	 t        di || _        y# t        $ rX}|dk7  rH	 | j                  |       n$# t        $ r}|j                  |       |d}~ww xY wt        di || _        n Y d}~yd}~ww xY w)z2Establish new connection (and/or autospawn server)FNr   )r]   _connr   _server_spawnrT   r/   )r$   r  r	  ceses        r   r  z"SSIPClient._connect_with_autospawnK  s}    	)<O<DJ% 	E!&&7! //3H .@@
 	s3    	A4A/4A/	AAAA//A4c                 V   |d|d|}| j                   j                  dt        j                  d|       | j                   j                  ddd      \  }}}t	        |d         | _        t        | j
                        | _        | j                   j                  | j                         t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  fD ]!  }| j                   j                  ddd	|d
       # y)zIInitialize connection -- Set client name, get id, register callbacks etc.:r   CLIENT_NAMEHISTORYGET	CLIENT_IDr   r$   r   onN)r  r   r   r   r   r   r   _callback_handlerr   r   r   r   r   r   r   r   )	r$   r  ra   r  	full_namerE   rF   rG   events	            r   r  z!SSIPClient._initialize_connection]  s    "&i8	

uzz=)L**11)UKPc4d1g,!1$//!B

 6 67"--"(("&&"))"(("))+ 	PE JJ##E6>5$O	Pr   c                 t   i }|j                  d      }	 |d   }||d<   |t        j                  k(  r	 |d   |d<   |S |t        j
                  k(  r	 |d   |d<   t        |d         |d	<   |S t        d      #  t        d      xY w# t        $ r Y |S w xY w# t        $ r t        d
      t        $ r Y |S w xY w)z^Parse a Speech Dispatcher address line and return a dictionary
        of connection argumentsr  r   zWrong format of server addressrv   r   rw   rx   r   ry   z<Third parameter of inet_socket address must be a port numberz(Unknown communication method in address.)	splitSSIPCommunicationErrrorrV   rZ   
IndexErrorr[   r   rg   r   )r$   r  r  address_params_methods        r   r  z-SSIPClient._connection_arguments_from_addressm  s     s+	L$Q'G 3:./)5551?1B.  +777*8*;'*-nQ.?*@'  ))STT#	L)*JKK
     m,-kll  	s.   A7 B B 7B	BBB76B7c                 $    | j                          y)zClose the connectionN)r   r*   s    r   __del__zSSIPClient.__del__  s    

r   c                 0   |d   dk(  rxt        j                  |d   |d         }|D cg c]
  }|d   d    }}d}|D ]   }|j                  d      s|d	k(  s||d<   d
}" |st        d|d   dt	        |      d      t        j                  d      }|st        j                  }t
        j                  j                  |      rg }|j                         D ]-  \  }	}
|	dvs|d|	j                  dd      z   t	        |
      gz  }/ t        j                  |dg|z   dt        j                  t        j                        }|j!                         \  }}|j#                         }|dk7  rt        d|      |j$                  S t        d|z        c c}w )z/Attempts to spawn the speech-dispatcher server.rv   rX   rx   ry   r   r   Fz127.z::1Tz@Can't start server automatically (autospawn), requested address z resolves on zj which seems to be a remote host. You must start the server manually or choose another connection address.SPEECHD_CMD)rx   z--_r   z--spawnN)stdinstdoutstderrz2Server refused to autospawn, stating this reason: z-Can't find Speech Dispatcher spawn command %s)rc   getaddrinfor   rT   r6   r   getenvr   SPD_SPAWN_CMDr   existsitemsr   
subprocessPopenPIPEcommunicatewaitpid)r$   r  	addrinfosaddrinfoip_addresses	localhostipr   connection_paramsparamvalueserverstdout_replystderr_replyretcodes                  r   r  zSSIPClient._server_spawn  s    12mC**?6+B+:6+BDI <EExHQKNELEI" #==(B%K.0OF+"I#  ! P__eOfORS_O`cd d
 ii&%%C77>># " / 5 5 7 Su	)%$u}}S/E*Es5z)RR%S  %%sI&67H&H,0Q[Q`Q`bF)/););)=&L,kkmG!| [g!ijj::L,/1 2 2? Fs   Fc                    |t         j                  t         j                  t         j                  t         j                  t         j
                  fv sJ |       | j                  j                  dt        j                  d|       y)zSet the priority category for the following messages.

        Arguments:
          priority -- one of the 'Priority' constants.

        r   PRIORITYN)
r   r   r   r   r   r   r  r   r   r   )r$   prioritys     r   set_priorityzSSIPClient.set_priority  si     H..0@0@$MM8+@+@$--/ / 	908	9 / 	

uzz:xHr   c                     |t         j                  k(  rd}n$|t         j                  k(  rd}nt        d|z        | j                  j                  dt        j                  d|       y)zSet the data mode for further speech commands.

        Arguments:
          value - one of the constants defined by the DataMode class.

        r  offz?Value "%s" is not one of the constants from the DataMode class.r   	SSML_MODEN)r   r   r   rg   r  r   r   r   )r$   rA  ssip_vals      r   set_data_modezSSIPClient.set_data_mode  s\     HMM!Hhmm#HQ  	

uzz;Ir   c                     | j                   j                  d       | j                   j                  |      }|r.t        |d   d         }| j                  j                  |||       |S )a  Say given message.

        Arguments:
          text -- message text to be spoken.  This may be either a UTF-8
            encoded byte string or a Python unicode string.
          callback -- a callback handler for asynchronous event notifications.
            A callable object (function) which accepts one positional argument
            `type' and one keyword argument `index_mark'.  See below for more
            details.
          event_types -- a tuple of event types for which the callback should
            be called.  Each item must be one of `CallbackType' constants.
            None (the default value) means to handle all event types.  This
            argument is irrelevant when `callback' is not used.

        The callback function will be called whenever one of the events occurs.
        The event type will be passed as argument.  Its value is one of the
        `CallbackType' constants.  In case of an index mark event, additional
        keyword argument `index_mark' will be passed and will contain the index
        mark identifier as specified within the text.

        The callback function should not perform anything complicated and is
        not allowed to issue any further SSIP client commands.  An attempt to
        do so would lead to a deadlock in SSIP communication.

        This method is non-blocking;  it just sends the command, given
        message is queued on the server and the method returns immediately.

        SPEAKr   r   )r  r   r   r   r  r   )r$   r   r   r   resultr   s         r   speakzSSIPClient.speak  s^    : 	

(%%d+1&F ""//+Nr   c                 \    | j                   j                  d|j                  dd             y)a>  Say given character.

        Arguments:
          char -- a character to be spoken.  Either a Python unicode string or
            a UTF-8 encoded byte string.

        This method is non-blocking;  it just sends the command, given
        message is queued on the server and the method returns immediately.

        CHARr   spaceN)r  r   r   )r$   chars     r   rV  zSSIPClient.char  s#     	

S'(BCr   c                 <    | j                   j                  d|       y)a  Say given key name.

        Arguments:
          key -- the key name (as defined in SSIP); string.

        This method is non-blocking;  it just sends the command, given
        message is queued on the server and the method returns immediately.

        KEYNr  r   )r$   keys     r   rZ  zSSIPClient.key	  s     	

s+r   c                 <    | j                   j                  d|       y)a  Output given sound_icon.

        Arguments:
          sound_icon -- the name of the sound icon as defined by SSIP; string.

        This method is non-blocking; it just sends the command, given message
        is queued on the server and the method returns immediately.

        
SOUND_ICONNrY  )r$   
sound_icons     r   r]  zSSIPClient.sound_icon  s     	

j9r   c                 <    | j                   j                  d|       y)zImmediately stop speaking and discard messages in queues.

        Arguments:
          scope -- see the documentation of this class.
            
        r   NrY  r$   scopes     r   r
   zSSIPClient.cancel!  s     	

%0r   c                 <    | j                   j                  d|       y)zImmediately stop speaking the currently spoken message.

        Arguments:
          scope -- see the documentation of this class.
        
        r   NrY  r_  s     r   stopzSSIPClient.stop+  s     	

.r   c                 <    | j                   j                  d|       y)a=  Pause speaking and postpone other messages until resume.

        This method is non-blocking.  However, speaking can continue for a
        short while even after it's called (typically to the end of the
        sentence).

        Arguments:
          scope -- see the documentation of this class.
        
        r   NrY  r_  s     r   r   zSSIPClient.pause4  s     	

/r   c                 <    | j                   j                  d|       y)a6  Resume speaking of the currently paused messages.

        This method is non-blocking.  However, speaking can continue for a
        short while even after it's called (typically to the end of the
        sentence).

        Arguments:
          scope -- see the documentation of this class.
        
        r   NrY  r_  s     r   r   zSSIPClient.resumeA  s     	

%0r   c                 F    | j                   j                  dd      \  }}}|S )z@Return names of all active output modules as a tuple of strings.LISTOUTPUT_MODULESrY  rD   s       r   list_output_moduleszSSIPClient.list_output_modulesN  s$    **11&:JKc4r   c                     	 ddg}|r$|j                  |       |r|j                  |        | j                  j                  | \  }}}d }t	        |D cg c]
  } ||       c}      S # t        $ r Y yw xY wc c}w )a  Return names of all available voices for the current output module.

        If language (possibly even variant) is set, only the list matching that
        language (possibly even variant) is returned.

        Returns a tuple of tripplets (name, language, variant).

        'name' is a string, 'language' is an ISO 639-1 Alpha-2/3 language code
        and 'variant' is a string.  Language and variant may be None.

        rf  SYNTHESIS_VOICESr   c                 Z    t        | j                  dd            \  }}}||xs d |xs d fS )N	r   )r   rsplit)itemra   langvariants       r   r"  z/SSIPClient.list_synthesis_voices.<locals>.splith  s3    "'D!(<"=D$$,$488r   )r5   r  r   rL   r   )	r$   languagerp  rO   rE   rF   rG   r"  rn  s	            r   list_synthesis_voicesz SSIPClient.list_synthesis_voicesS  s    	12Gx(NN7+5djj55w?OD#t	9 d3deDk344   		
 4s   AA+ A:+	A76A7c                 d    t        |t              sJ | j                  j                  d|d|       y)a  Switch to a particular language for further speech commands.

        Arguments:
          language -- two/three letter language code according to RFC 1766 as string, possibly with a region qualification.
          scope -- see the documentation of this class.
            
        r   LANGUAGEN)r   r6   r  r   )r$   rq  r`  s      r   set_languagezSSIPClient.set_languagem  s,     (C(((

uj(Cr   c                 R    | j                   j                  dd      \  }}}|r|d   S y)zGet the current language.r  rt  r   NrY  rD   s       r   get_languagezSSIPClient.get_languagex  s-    **11%Dc47Nr   c                 @    | j                   j                  d|d|       y)zSwitch to a particular output module.

        Arguments:
          name -- module (string) as returned by 'list_output_modules()'.
          scope -- see the documentation of this class.
        
        r   OUTPUT_MODULENrY  )r$   ra   r`  s      r   set_output_modulezSSIPClient.set_output_module  s     	

uotDr   c                 R    | j                   j                  dd      \  }}}|r|d   S y)zGet the current output module.r  ry  r   NrY  rD   s       r   get_output_modulezSSIPClient.get_output_module  s-    **11%Ic47Nr   c                     t        |t              rd|cxk  rdk  sJ |        J |       | j                  j                  d|d|       y)a  Set the pitch for further speech commands.

        Arguments:
          value -- integer value within the range from -100 to 100, with 0
            corresponding to the default pitch of the current speech synthesis
            output module, lower values meaning lower pitch and higher values
            meaning higher pitch.
          scope -- see the documentation of this class.
          
        r   r   PITCHNr   r   r  r   r$   rA  r`  s      r   	set_pitchzSSIPClient.set_pitch  sK     %%$%*>3*>EE>*>EE>

ugu=r   c                 R    | j                   j                  dd      \  }}}|r|d   S y)zGet the current pitch.r  r  r   NrY  rD   s       r   	get_pitchzSSIPClient.get_pitch  s-    **11%Ac47Nr   c                     t        |t              rd|cxk  rdk  sJ |        J |       | j                  j                  d|d|       y)a  Set the pitch range for further speech commands.

        Arguments:
          value -- integer value within the range from -100 to 100, with 0
            corresponding to the default pitch range of the current speech synthesis
            output module, lower values meaning lower pitch range and higher values
            meaning higher pitch range.
          scope -- see the documentation of this class.
          
        r~  r   r   PITCH_RANGENr  r  s      r   set_pitch_rangezSSIPClient.set_pitch_range  sK     %%$%*>3*>EE>*>EE>

umUCr   c                     t        |t              rd|cxk  rdk  sJ  J | j                  j                  d|d|       y)a  Set the speech rate (speed) for further speech commands.

        Arguments:
          value -- integer value within the range from -100 to 100, with 0
            corresponding to the default speech rate of the current speech
            synthesis output module, lower values meaning slower speech and
            higher values meaning faster speech.
          scope -- see the documentation of this class.
            
        r~  r   r   RATENr  r  s      r   set_ratezSSIPClient.set_rate  sA     %%$%*>3*>>>*>>>

ufe<r   c                 R    | j                   j                  dd      \  }}}|r|d   S y)z$Get the current speech rate (speed).r  r  r   NrY  rD   s       r   get_ratezSSIPClient.get_rate  s-    **11%@c47Nr   c                     t        |t              rd|cxk  rdk  sJ  J | j                  j                  d|d|       y)aw  Set the speech volume for further speech commands.

        Arguments:
          value -- integer value within the range from -100 to 100, with 100
            corresponding to the default speech volume of the current speech
            synthesis output module, lower values meaning softer speech.
          scope -- see the documentation of this class.
            
        r~  r   r   VOLUMENr  r  s      r   
set_volumezSSIPClient.set_volume  sA     %%$%*>3*>>>*>>>

uh>r   c                 R    | j                   j                  dd      \  }}}|r|d   S y)zGet the speech volume.r  r  r   NrY  rD   s       r   
get_volumezSSIPClient.get_volume  s-    **11%Bc47Nr   c                     |t         j                  t         j                  t         j                  t         j                  fv sJ |       | j
                  j                  d|d|       y)zSet the punctuation pronunciation level.

        Arguments:
          value -- one of the 'PunctuationMode' constants.
          scope -- see the documentation of this class.
            
        r   PUNCTUATIONN)r   r   r   r   r   r  r   r  s      r   set_punctuationzSSIPClient.set_punctuation  sa     ,,o.B.B(--/C/CE E 	LFK	L E

umUCr   c                 R    | j                   j                  dd      \  }}}|r|d   S y)z(Get the punctuation pronunciation level.r  r  r   NrY  rD   s       r   get_punctuationzSSIPClient.get_punctuation  s-    **11%Gc47Nr   c                     |dv sJ |dk(  r| j                   j                  d|dd       y| j                   j                  d|dd       y)a,  Toggle the spelling mode or on off.

        Arguments:
          value -- if 'True', all incoming messages will be spelled
            instead of being read as normal words. 'False' switches
            this behavior off.
          scope -- see the documentation of this class.
            
        )TFTr   SPELLINGr  rK  NrY  r  s      r   set_spellingzSSIPClient.set_spelling  sI     %%%D=JJ##E5*dCJJ##E5*eDr   c                 L    |dv sJ | j                   j                  d|d|       y)a  Set capital letter recognition mode.

        Arguments:
          value -- one of 'none', 'spell', 'icon'. None means no signalization
            of capital letters, 'spell' means capital letters will be spelled
            with a synthetic voice and 'icon' means that the capital-letter icon
            will be prepended before each capital letter.
          scope -- see the documentation of this class.
            
        )r   spelliconr   CAP_LET_RECOGNNrY  r  s      r   set_cap_let_recognzSSIPClient.set_cap_let_recogn  s,     1111

u.>Fr   c                     t        |t              r|j                         dv sJ | j                  j	                  d|d|       y)a  Set voice by a symbolic name.

        Arguments:
          value -- one of the SSIP symbolic voice names: 'MALE1' .. 'MALE3',
            'FEMALE1' ... 'FEMALE3', 'CHILD_MALE', 'CHILD_FEMALE'
          scope -- see the documentation of this class.

        Symbolic voice names are mapped to real synthesizer voices in the
        configuration of the output module.  Use the method
        'set_synthesis_voice()' if you want to work with real voices.
            
        )male1male2male3female1female2female3
child_malechild_femaler   
VOICE_TYPEN)r   r6   lowerr  r   r  s      r   	set_voicezSSIPClient.set_voice  sE     %%{{} !1 1	1 1 	

ulEBr   c                 @    | j                   j                  d|d|       y)zSet voice by its real name.

        Arguments:
          value -- voice name as returned by 'list_synthesis_voices()'
          scope -- see the documentation of this class.
            
        r   SYNTHESIS_VOICENrY  r  s      r   set_synthesis_voicezSSIPClient.set_synthesis_voice   s     	

u.?Gr   c                 d    t        |t              sJ | j                  j                  d|d|       y)a;  Set the amount of context when resuming a paused message.

        Arguments:
          value -- a positive or negative value meaning how many chunks of data
            after or before the pause should be read when resume() is executed.
          scope -- see the documentation of this class.
            
        r   PAUSE_CONTEXTNr  r  s      r   set_pause_contextzSSIPClient.set_pause_context*  s,     %%%%

uouEr   c                     t        |t              sJ |dk(  rd}nd}| j                  j                  dt        j
                  d|       y)a  Switch debugging on and off. When switched on,
        debugging files will be created in the chosen destination
        (see set_debug_destination()) for Speech Dispatcher and all
        its running modules. All logging information will then be
        written into these files with maximal verbosity until switched
        off. You should always first call set_debug_destination.

        The intended use of this functionality is to switch debugging
        on for a period of time while the user will repeat the behavior
        and then send the logs to the appropriate bug-reporting place.

        Arguments:
          val -- a boolean value determining whether debugging
                 is switched on or off
          scope -- see the documentation of this class.
        
        TONOFFr   DEBUGN)r   boolr  r   r`  r   )r$   valrM  s      r   	set_debugzSSIPClient.set_debug6  sA    $ #t$$$$;HH

uyy'8Dr   c                     t        t        t              sJ | j                  j	                  dt
        j                  dt               y)zSet debug destination.

        Arguments:
          path -- path (string) to the directory where debugging
                  files will be created
          scope -- see the documentation of this class.
        
        r   DEBUG_DESTINATIONN)r   r  stringr  r   r`  r   )r$   r   s     r   set_debug_destinationz SSIPClient.set_debug_destinationQ  s1     #v&&&

uyy2EsKr   c                 <    | j                   j                  dd       y)z]Begin an SSIP block.

        See SSIP documentation for more details about blocks.

        BLOCKr   NrY  r*   s    r   block_beginzSSIPClient.block_begin^  s     	

1r   c                 <    | j                   j                  dd       y)z]Close an SSIP block.

        See SSIP documentation for more details about blocks.

        r  r   NrY  r*   s    r   	block_endzSSIPClient.block_endf  s     	

/r   c                 V    t        | d      r| j                  j                          | `yy)z*Close the connection to Speech Dispatcher.r  N)hasattrr  r   r*   s    r   r   zSSIPClient.closen  s&    4!JJ
 "r   )defaultunknownNNNNNNr:   )2r   r   r   r   r   r  r   r#   r  r  r  r(  r  rI  rN  rR  rV  rZ  r]  r   r   r
   rb  r   r   rh  rr  ru  rw  rz  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   r   r     s   * L.L5:7JN@DM;^$P 6*2X
IJ"%ND
,
: !:: 1  /  ** 0 !:: 1
54 ,1:: 	D -2JJ E &+ZZ > ,1:: D %*JJ = ',jj ? ,1:: 
D ).

 E  /4jj G &+ZZ C& 05zz H .3ZZ 
FE6L20r   r   c                        e Zd ZdZd fd	Zej                  fdZej                  f fd	Z	ej                  f fd	Z
ej                  f fd	Z xZS )Clienta0  A DEPRECATED backwards-compatible API.

    This Class is provided only for backwards compatibility with the previous
    unofficial API.  It will be removed in future versions.  Please use either
    'SSIPClient' or 'Speaker' interface instead.  As deprecated, the API is no
    longer documented.

    c                 B    |xs |xs d}t        t        | 
  |fi | y )Npython)r"   r  r#   )r$   ra   clientr'   r(   s       r   r#   zClient.__init__~  s&    )v)fd$T4V4r   c                 H    | j                  |       | j                  |       y r   )rI  rR  )r$   r   rH  s      r   sayz
Client.say  s    (#

4r   c                 N    | j                  |       t        t        |   |       y r   )rI  r"   r  rV  )r$   rV  rH  r(   s      r   rV  zClient.char  s     (#fd &r   c                 N    | j                  |       t        t        |   |       y r   )rI  r"   r  rZ  )r$   rZ  rH  r(   s      r   rZ  z
Client.key  s     (#fd$r   c                 N    | j                  |       t        t        |   |       y r   )rI  r"   r  r]  )r$   r]  rH  r(   s      r   r]  zClient.sound_icon  s     (#fd&z2r   r:   )r   r   r   r   r#   r   r   r  r   rV  rZ  r]  r;   r<   s   @r   r  r  u  sL    5 "*!1!1  #+-- ' !) % /7mm 3 3r   r  c                       e Zd ZdZy)Speakera  Extended Speech Dispatcher Interface.

    This class provides an extended intercace to Speech Dispatcher
    functionality and tries to hide most of the lower level details of SSIP
    (such as a more sophisticated handling of blocks and priorities and
    advanced event notifications) under a more convenient API.
    
    Please note that the API is not yet stabilized and thus is subject to
    change!  Please contact the authors if you plan using it and/or if you have
    any suggestions.

    Well, in fact this class is currently not implemented at all.  It is just a
    draft.  The intention is to hide the SSIP details and provide a generic
    interface practical for screen readers.
    
    Nr   r   r   r   r  r    s    r   r  c                       e Zd ZdZdZ	 dZy)ConnectionMethodzConstants describing the possible methods of connection to server.

    Retained for backwards compatibility but DEPRECATED. See CommunicationMethod.rW   rX   NrY   r   r   r   r  r    s    U  K;K9r   r  )r   rc   r   r   r4  timetempfilero   dummy_threading r   objectr   r@   r   r   r>   rL   rQ   rT   rV   r]   r   r   r   r   r   r   r  r  r  r   r   r   <module>r     s    3 2 2( )6 ).F	 F,Y ,\	  ( % 1 1:& :l"v l"\!v !B
LF 
Lv f &;v ;S
 S
l3Z 3<j ,:v :U$('s   C- -C5