3
ѤZų              
   @   s  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yddlZW n   ddlZY nX ddl	m
Z
 G dd deZG dd deZG d	d
 d
eZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd  d eZG d!d" d"eZG d#d$ d$eZG d%d& d&eZG d'd( d(eZdS ))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               @   s(   e Zd ZdZdZdZdZdZdZdZ	dS )	CallbackTypez5Constants describing the available types of callbacksZindex_marksZbeginendcancelpauseresumeN)
__name__
__module____qualname____doc__
INDEX_MARKBEGINENDCANCELPAUSERESUME r   r   0/usr/lib/python3/dist-packages/speechd/client.pyr   %   s   r   c               @   s   e Zd ZdZdS )	SSIPErrorz;Common base class for exceptions during SSIP communication.N)r	   r
   r   r   r   r   r   r   r   <   s   r   c                   sN   e Zd ZdZdZd fdd	Zdd Zdd Zd	d
 Zdd Z	dd Z
  ZS )SSIPCommunicationErrorz?Exception raised when trying to operate on a closed connection.Nc                s"   || _ || _tt| jf | d S )N)_original_exception_descriptionsuperr   __init__)selfdescriptionoriginal_exceptionkwargs)	__class__r   r   r   D   s    zSSIPCommunicationError.__init__c             C   s   | 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   r   r   r   r   I   s    z)SSIPCommunicationError.original_exceptionc             C   s
   || _ dS )zXSet an additional exception
        
        See method additional_exception().
        N)_additional_exception)r   Z	exceptionr   r   r   set_additional_exceptionQ   s    z/SSIPCommunicationError.set_additional_exceptionc             C   s   | j S )zReturn an additional exception
        
        Additional exceptions araise from failed attempts to resolve
        the former problem)r    )r   r   r   r   additional_exceptionX   s    z+SSIPCommunicationError.additional_exceptionc             C   s   | j S )zReturn error description)r   )r   r   r   r   r   _   s    z"SSIPCommunicationError.descriptionc             C   s\   g }| j  r|j| j   | jr6|jdt| j   | jrR|jdt| j   dj|S )NzOriginal error: zAdditional error: 
)r   appendr   strr"   join)r   Zmsgsr   r   r   __str__c   s    zSSIPCommunicationError.__str__)NN)r	   r
   r   r   r    r   r   r!   r"   r   r'   __classcell__r   r   )r   r   r   ?   s   r   c               @   s$   e Zd Zdd Zdd Zdd ZdS )SSIPResponseErrorc             C   s*   t j| d||f  || _|| _|| _d S )Nz%s: %s)	Exceptionr   _code_msg_data)r   codemsgdatar   r   r   r   n   s    zSSIPResponseError.__init__c             C   s   | j S )z8Return the server response error code as integer number.)r+   )r   r   r   r   r.   t   s    zSSIPResponseError.codec             C   s   | j S )z/Return server response error message as string.)r,   )r   r   r   r   r/   x   s    zSSIPResponseError.msgN)r	   r
   r   r   r.   r/   r   r   r   r   r)   m   s   r)   c               @   s   e Zd ZdZdd ZdS )SSIPCommandErrorz9Exception raised on error response after sending command.c             C   s   | j S )z7Return the command string which resulted in this error.)r-   )r   r   r   r   command   s    zSSIPCommandError.commandN)r	   r
   r   r   r2   r   r   r   r   r1   }   s   r1   c               @   s   e Zd ZdZdd ZdS )SSIPDataErrorz6Exception raised on error response after sending data.c             C   s   | j S )z-Return the data which resulted in this error.)r-   )r   r   r   r   r0      s    zSSIPDataError.dataN)r	   r
   r   r   r0   r   r   r   r   r3      s   r3   c               @   s   e Zd ZdZdS )
SpawnErrorz&Indicates failure in server autospawn.N)r	   r
   r   r   r   r   r   r   r4      s   r4   c               @   s   e Zd ZdZdZdZdS )CommunicationMethodzBConstants describing the possible methods of connection to server.unix_socketinet_socketN)r	   r
   r   r   UNIX_SOCKETINET_SOCKETr   r   r   r   r5      s   r5   c               @   s   e Zd ZdZdZdZdZee e Zee e Zee Z	ee Z
ejejejejejejdZdd Zdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd ZdS )_SSIP_Connectionz/Implemantation of low level SSIP communication.s   
   .s   ..)i  i  i  i  i  i  c             C   s   |t jkrtj}|}n4|t jkrB|r(|s,ttj}tj||f}ntdy tj|tj	| _
| j
j| W n4 tjk
r } ztd| |dW Y dd}~X nX d| _g | _d| _tjd| _tj| ji dd| _| jj  dS )	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   N    r   z SSIP client communication thread)targetr   name)r5   r8   socketZAF_UNIXr9   AssertionErrorZAF_INETZgethostbyname
ValueErrorZSOCK_STREAM_socketZconnecterrorr   _buffer_com_buffer	_callback	threadingZ	Semaphore_ssip_reply_semaphoreZThread_communication_communication_threadstart)r   communication_methodsocket_pathhostportZsocket_familyZsocket_connect_argsexr   r   r   r      s,    



z_SSIP_Connection.__init__c             C   sB   y| j jtj W n tjk
r(   Y nX | j j  | jj  dS )z>Close the server connection, destroy the communication thread.N)rB   Zshutdownr?   Z	SHUT_RDWRrC   closerJ   r&   )r   r   r   r   rQ      s    
z_SSIP_Connection.closec             C   s   xy| j  \}}}W n tk
r0   tj  Y nX |d dkr\| jj|||f | jj  q| jdk	r| j	| }|t
jkrd|d i}ni }tt|dd \}}| j|||f| qW dS )a,  Handle incomming socket communication.

        Listens for all incomming 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      NZ
index_mark   )_recv_messageIOErrorsysexitrE   r$   rH   releaserF   _CALLBACK_TYPE_MAPr   r   mapint)r   r.   r/   r0   typer   msg_id	client_idr   r   r   rI      s     



z_SSIP_Connection._communicationc          	   C   s   | j j| j}xZ|dkrhy| jjd}W n   tY nX t|dkrJt|  j |7  _ | j j| j}qW | j d| }| j |t| j d | _ |jdS )zuRead one whole line from the socket.

        Blocks until the line delimiter ('_NEWLINE') is read.
        
        r   i   r   Nzutf-8)rD   find_NEWLINErB   ZrecvrV   lendecode)r   Zpointerdliner   r   r   	_readline   s    

z_SSIP_Connection._readlinec             C   s   g }d}x| j  }t|dks&td|dd |d |dd   }}}|j rj|dksb||krj|dksrtd|dkr|}t||t|fS |j| q
W dS )zTRead server response or a callback
        and return the triplet (code, msg, data).N   z$Malformed data received from server!   - )rj   rk   )rg   rc   r@   isalnumr\   tupler$   )r   r0   crf   r.   septextr/   r   r   r   rU     s    $z_SSIP_Connection._recv_messagec             C   s.   | 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   )rJ   ZisAliver   rH   acquirerE   )r   Zresponser   r   r   _recv_response   s    


z_SSIP_Connection._recv_responsec             G   s   |d
kr.|d t jt jfks.t|d ts.tdj|fttt	| }y| j
j|jd| j  W n tjk
r   tdY nX | j \}}}|d d	krt||||||fS )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   rk   zutf-8z"Speech Dispatcher connection lost.rR   rT   )rs   r   rt   )ScopeSELFALL
isinstancer\   r@   r&   rm   r[   r%   rB   sendencoderb   r?   rC   r   rr   r1   )r   r2   argscmdr.   r/   r0   r   r   r   send_command-  s    z_SSIP_Connection.send_commandc             C   s   |j d}|j| jr2t| j}| j||d  }|j| j| j}y| jj	|| j
  W n tjk
rv   tdY nX | j \}}}|d dkrt||||||fS )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.
        
        zutf-8Nz"Speech Dispatcher connection lost.rR   rT   )rz   
startswith_END_OF_DATA_MARKERrc   _END_OF_DATA_MARKER_ESCAPEDreplace_RAW_DOTLINE_ESCAPED_DOTLINErB   ry   _END_OF_DATAr?   rC   r   rr   r3   )r   r0   lr.   r/   Zresponse_datar   r   r   	send_dataL  s    

z_SSIP_Connection.send_datac             C   s
   || _ dS )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)rF   )r   callbackr   r   r   set_callbackm  s    z_SSIP_Connection.set_callbackN)r	   r
   r   r   rb   r   r   r   Z_END_OF_DATA_ESCAPEDr   r   r   r   r   r   r   r   r   rZ   r   rQ   rI   rg   rU   rr   r}   r   r   r   r   r   r   r:      s.   
!$!r:   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_CallbackHandlerz(Internal object which handles callbacks.c             C   s   || _ i | _tj | _d S )N)
_client_id
_callbacksrG   ZLock_lock)r   r_   r   r   r   r     s    z_CallbackHandler.__init__c             K   s   || j krd S | jj  z`y| j| \}}W n tk
r@   Y n6X |d ksR||kr^||f| |tjtjfkrv| j|= W d | jj  X d S )N)	r   r   rq   r   KeyErrorr   r   r   rY   )r   r^   r_   r]   r   r   event_typesr   r   r   __call__  s    

z_CallbackHandler.__call__c          
   C   s.   | j j  z||f| j|< W d | j j  X d S )N)r   rq   r   rY   )r   r^   r   r   r   r   r   add_callback  s    
z_CallbackHandler.add_callbackN)r	   r
   r   r   r   r   r   r   r   r   r   r     s   r   c               @   s   e Zd ZdZdZdZdS )ru   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   rv   rw   r   r   r   r   ru     s   ru   c               @   s$   e Zd ZdZdZdZdZdZdZdS )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.
    
    Z	importantrp   messageZnotificationZprogressN)	r	   r
   r   r   	IMPORTANTTEXTMESSAGENOTIFICATIONPROGRESSr   r   r   r   r     s   r   c               @   s   e Zd ZdZdZdZdZdS )PunctuationModezkConstants for selecting a punctuation mode.

    The mode determines which characters should be read.

    r   noneZsomeN)r	   r
   r   r   rw   NONESOMEr   r   r   r   r     s
   r   c               @   s   e Zd ZdZdZdZdS )DataModezWConstants specifying the type of data contained within messages
    to be spoken.

    rp   ZssmlN)r	   r
   r   r   r   SSMLr   r   r   r   r     s   r   c               @   s  e Zd ZdZdZdZdZdVdd	Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdWddZdd Zdd Zdd Zejfd d!Zejfd"d#Zejfd$d%Zejfd&d'Zd(d) Zd*d+ Zejfd,d-Zd.d/ Zejfd0d1Zd2d3 Zejfd4d5Zd6d7 Z ejfd8d9Z!d:d; Z"ejfd<d=Z#d>d? Z$ejfd@dAZ%ejfdBdCZ&ejfdDdEZ'ejfdFdGZ(ejfdHdIZ)ejfdJdKZ*dLdM Z+dNdO Z,dPdQ Z-dRdS Z.dTdU Z/dS )X
SSIPClienta  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.

    z	127.0.0.1i  zspeech-dispatcher/speechd.sockdefaultunknownNc
          
   C   s  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}|p`t jjd}|rx|j| j| n~t jjd}ytt jjd}W n   d	}Y nX t jjd
}|r||d< |r||d< n|r||d< |	r|	|d< n|r||d< | j|| | j||| d	S )aZ  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
            acces 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.
        ~ZXDG_RUNTIME_DIRZXDG_CACHE_HOMEz.cache)rL   rM   rN   rO   ZSPEECHD_ADDRESSZSPEECHD_HOSTZSPEECHD_PORTNZSPEECHD_SOCKETmethodrO   rM   )ospath
expanduserenvirongetr&   DEFAULT_SOCKET_PATHr5   r8   DEFAULT_HOSTDEFAULT_PORTupdate"_connection_arguments_from_addressr\   _connect_with_autospawn_initialize_connection)r   r>   	componentuseraddress	autospawnrN   rO   r   rM   _homeZ_runtime_dirZ
_sock_pathconnection_argsZ_addressZenv_speechd_hostZenv_speechd_portZenv_speechd_socket_pathr   r   r   r     s8    '"



zSSIPClient.__init__c             C   s   yt f || _W nz tk
r } z^|dkrxy| j| W n0 tk
rh } z|j| |W Y dd}~X nX t f || _n W Y dd}~X nX dS )z2Establish new connection (and/or autospawn server)FN)r:   _connr   _server_spawnr4   r!   )r   r   r   ZceZser   r   r   r   C  s    
z"SSIPClient._connect_with_autospawnc       	      C   s   d|||f }| j jdtjd| | j jddd\}}}t|d | _t| j| _| j j| j x8t	j
t	jt	jt	jt	jt	jfD ]}| j jddd	|d
 q~W dS )zIInitialize connection -- Set client name, get id, register callbacks etc.z%s:%s:%srs   ZCLIENT_NAMEZHISTORYGETZ	CLIENT_IDr   r   r   onN)r   r}   ru   rv   r\   r   r   _callback_handlerr   r   r   r   r   r   r   r   )	r   r   r>   r   Z	full_namer.   r/   r0   Zeventr   r   r   r   U  s    z!SSIPClient._initialize_connectionc             C   s   i }|j d}y|d }W n   tdY nX ||d< |tjkrjy|d |d< W q tk
rf   Y qX nd|tjkry |d |d< t|d |d	< W q tk
r   td
Y q tk
r   Y qX ntd|S )z^Parse a Speech Dispatcher address line and return a dictionary
        of connection arguments:r   zWrong format of server addressrL   r   rM   rN   rT   rO   z<Third parameter of inet_socket address must be a port numberz(Unknown communication method in address.)	splitZSSIPCommunicationErrrorr5   r8   
IndexErrorr9   r\   rA   r   )r   r   r   Zaddress_params_methodr   r   r   r   e  s,    


z-SSIPClient._connection_arguments_from_addressc             C   s   | j   dS )zClose the connectionN)rQ   )r   r   r   r   __del__  s    zSSIPClient.__del__c             C   s.  |d dkrzt j|d |d }dd |D }d}x*|D ]"}|jdsN|d	kr8||d< d
}q8W |sztd|d t|f tjjtj	rg }x8|j
 D ],\}}|dkr|d|jdd t|g7 }qW tjtj	dg| dtjtjd}	|	j \}
}|	j }|dkrtd|f |	jS tdtj	f dS )z/Attempts to spawn the speech-dispatcher server.rL   r7   rN   rO   c             S   s   g | ]}|d  d qS )rh   r   r   ).0Zaddrinfor   r   r   
<listcomp>  s    z,SSIPClient._server_spawn.<locals>.<listcomp>Fz127.z::1TzCan't start server automatically (autospawn), requested address %s resolves on %s which seems to be a remote host. You must start the server manually or choose another connection address.z--_rj   z--spawnN)stdinstdoutstderrr   z4Server refused to autospawn, stating this reason: %sz-Can't find Speech Dispatcher spawn command %s)rN   )r?   Zgetaddrinfor~   r4   r%   r   r   existsr   ZSPD_SPAWN_CMDitemsr   
subprocessPopenPIPEZcommunicatewaitpid)r   r   Z	addrinfosZip_addressesZ	localhostZipZconnection_paramsZparamvalueZserverZstdout_replyZstderr_replyZretcoder   r   r   r     s8    


 
zSSIPClient._server_spawnc             C   s<   |t jt jt jt jt jfks$t|| jjdt	j
d| dS )zSet the priority category for the following messages.

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

        rs   ZPRIORITYN)r   r   r   r   r   r   r@   r   r}   ru   rv   )r   priorityr   r   r   set_priority  s    
zSSIPClient.set_priorityc             C   sD   |t jkrd}n|t jkr d}ntd| | jjdtjd| dS )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.rs   Z	SSML_MODEN)r   r   r   rA   r   r}   ru   rv   )r   r   ssip_valr   r   r   set_data_mode  s    

zSSIPClient.set_data_modec             C   s@   | 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.

        ZSPEAKrT   r   )r   r}   r   r\   r   r   )r   rp   r   r   resultr^   r   r   r   speak  s    zSSIPClient.speakc             C   s   | j jd|jdd dS )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.

        ZCHARrk   ZspaceN)r   r}   r   )r   charr   r   r   r     s    zSSIPClient.charc             C   s   | j jd| dS )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.

        ZKEYN)r   r}   )r   keyr   r   r   r     s    
zSSIPClient.keyc             C   s   | j jd| dS )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.

        Z
SOUND_ICONN)r   r}   )r   
sound_iconr   r   r   r   
  s    
zSSIPClient.sound_iconc             C   s   | j jd| dS )zImmediately stop speaking and discard messages in queues.

        Arguments:
          scope -- see the documentation of this class.
            
        r   N)r   r}   )r   scoper   r   r   r     s    zSSIPClient.cancelc             C   s   | j jd| dS )zImmediately stop speaking the currently spoken message.

        Arguments:
          scope -- see the documentation of this class.
        
        rt   N)r   r}   )r   r   r   r   r   stop   s    zSSIPClient.stopc             C   s   | j jd| dS )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   N)r   r}   )r   r   r   r   r   r   )  s    zSSIPClient.pausec             C   s   | j jd| dS )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   N)r   r}   )r   r   r   r   r   r   6  s    zSSIPClient.resumec             C   s   | j jdd\}}}|S )z@Return names of all active output modules as a tuple of strings.LISTZOUTPUT_MODULES)r   r}   )r   r.   r/   r0   r   r   r   list_output_modulesC  s    zSSIPClient.list_output_modulesc                sL   y| j jdd\}}}W n tk
r,   f S X dd  t fdd|D S )a"  Return names of all available voices for the current output module.

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

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

        r   ZSYNTHESIS_VOICESc             S   s(   t | jdd\}}}||pd |p$d fS )Nrk   ri   )rm   rsplit)itemr>   ZlangZdialectr   r   r   r   U  s    z/SSIPClient.list_synthesis_voices.<locals>.splitc                s   g | ]} |qS r   r   )r   r   )r   r   r   r   X  s    z4SSIPClient.list_synthesis_voices.<locals>.<listcomp>)r   r}   r1   rm   )r   r.   r/   r0   r   )r   r   list_synthesis_voicesH  s    	z SSIPClient.list_synthesis_voicesc             C   s0   t |trt|dkst| jjd|d| dS )zSwitch to a particular language for further speech commands.

        Arguments:
          language -- two letter language code according to RFC 1766 as string.
          scope -- see the documentation of this class.
            
        rT   rs   LANGUAGEN)rx   r%   rc   r@   r   r}   )r   Zlanguager   r   r   r   set_languageZ  s    zSSIPClient.set_languagec             C   s$   | j jdd\}}}|r |d S dS )zGet the current language.r   r   r   N)r   r}   )r   r.   r/   r0   r   r   r   get_languagee  s    zSSIPClient.get_languagec             C   s   | j jd|d| dS )zSwitch to a particular output module.

        Arguments:
          name -- module (string) as returned by 'list_output_modules()'.
          scope -- see the documentation of this class.
        
        rs   OUTPUT_MODULEN)r   r}   )r   r>   r   r   r   r   set_output_modulel  s    zSSIPClient.set_output_modulec             C   s$   | j jdd\}}}|r |d S dS )zGet the current output module.r   r   r   N)r   r}   )r   r.   r/   r0   r   r   r   get_output_modulev  s    zSSIPClient.get_output_modulec             C   s@   t |tr"d|  kodkn  s*t|| jjd|d| dS )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.
          
        rR   rs   PITCHNi)rx   r\   r@   r   r}   )r   r   r   r   r   r   	set_pitch}  s    *zSSIPClient.set_pitchc             C   s$   | j jdd\}}}|r |d S dS )zGet the current pitch.r   r   r   N)r   r}   )r   r.   r/   r0   r   r   r   	get_pitch  s    zSSIPClient.get_pitchc             C   s<   t |tr"d|  kodkn  s&t| jjd|d| dS )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.
            
        rR   rs   RATENi)rx   r\   r@   r   r}   )r   r   r   r   r   r   set_rate  s    &zSSIPClient.set_ratec             C   s$   | j jdd\}}}|r |d S dS )z$Get the current speech rate (speed).r   r   r   N)r   r}   )r   r.   r/   r0   r   r   r   get_rate  s    zSSIPClient.get_ratec             C   s<   t |tr"d|  kodkn  s&t| jjd|d| dS )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.
            
        rR   rs   VOLUMENi)rx   r\   r@   r   r}   )r   r   r   r   r   r   
set_volume  s    
&zSSIPClient.set_volumec             C   s$   | j jdd\}}}|r |d S dS )zGet the speech volume.r   r   r   N)r   r}   )r   r.   r/   r0   r   r   r   
get_volume  s    zSSIPClient.get_volumec             C   s2   |t jt jt jfkst|| jjd|d| dS )zSet the punctuation pronounciation level.

        Arguments:
          value -- one of the 'PunctuationMode' constants.
          scope -- see the documentation of this class.
            
        rs   ZPUNCTUATIONN)r   rw   r   r   r@   r   r}   )r   r   r   r   r   r   set_punctuation  s    
zSSIPClient.set_punctuationc             C   s>   |dkst |dkr(| jjd|dd n| jjd|dd dS )	a-  Toogle the spelling mode or on off.

        Arguments:
          value -- if 'True', all incomming messages will be spelled
            instead of being read as normal words. 'False' switches
            this behavior off.
          scope -- see the documentation of this class.
            
        TFrs   ZSPELLINGr   r   N)TF)r@   r   r}   )r   r   r   r   r   r   set_spelling  s    
zSSIPClient.set_spellingc             C   s"   |dkst | jjd|d| dS )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 syntetic 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iconrs   ZCAP_LET_RECOGNN)r   r   r   )r@   r   r}   )r   r   r   r   r   r   set_cap_let_recogn  s    zSSIPClient.set_cap_let_recognc          	   C   s0   t |tr|j dkst| jjd	|d
| dS )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_femalers   Z
VOICE_TYPEN)r   r   r   r   r   r   r   r   )rx   r%   lowerr@   r   r}   )r   r   r   r   r   r   	set_voice  s
    
 
zSSIPClient.set_voicec             C   s   | j jd|d| dS )zSet voice by its real name.

        Arguments:
          value -- voice name as returned by 'list_synthesis_voices()'
          scope -- see the documentation of this class.
            
        rs   ZSYNTHESIS_VOICEN)r   r}   )r   r   r   r   r   r   set_synthesis_voice  s    zSSIPClient.set_synthesis_voicec             C   s$   t |tst| jjd|d| dS )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.
            
        rs   ZPAUSE_CONTEXTN)rx   r\   r@   r   r}   )r   r   r   r   r   r   set_pause_context  s    	zSSIPClient.set_pause_contextc             C   s8   t |tst|dkrd}nd}| jjdtjd| dS )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 debuging
        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.
        
        TZONZOFFrs   DEBUGN)rx   boolr@   r   r}   r   rw   )r   valr   r   r   r   	set_debug  s
    zSSIPClient.set_debugc             C   s&   t ttst| jjdtjdt dS )zSet debug destination.

        Arguments:
          path -- path (string) to the directory where debuging
                  files will be created
          scope -- see the documentation of this class.
        
        rs   ZDEBUG_DESTINATIONN)rx   r  stringr@   r   r}   r   rw   )r   r   r   r   r   set_debug_destination)  s    	z SSIPClient.set_debug_destinationc             C   s   | j jdd dS )z]Begin an SSIP block.

        See SSIP documentation for more details about blocks.

        BLOCKr   N)r   r}   )r   r   r   r   block_begin6  s    zSSIPClient.block_beginc             C   s   | j jdd dS )z]Close an SSIP block.

        See SSIP documentation for more details about blocks.

        r  r   N)r   r}   )r   r   r   r   	block_end>  s    zSSIPClient.block_endc             C   s   t | dr| jj  | `dS )z*Close the connection to Speech Dispatcher.r   N)hasattrr   rQ   )r   r   r   r   rQ   F  s    

zSSIPClient.close)r   r   NNNNNN)NN)0r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ru   rv   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  r  rQ   r   r   r   r   r     sZ     
L)
'
	

r   c                   sf   e Zd ZdZd fdd	ZejfddZejf fdd	Z	ejf fd	d
	Z
ejf fdd	Z  ZS )Clienta0  A DEPRECATED backwards-compatible API.

    This Class is provided only for backwards compatibility with the prevoius
    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.

    Nc                s$   |p
|p
d}t t| j|f| d S )Npython)r   r	  r   )r   r>   Zclientr   )r   r   r   r   V  s    zClient.__init__c             C   s   | j | | j| d S )N)r   r   )r   rp   r   r   r   r   sayZ  s    
z
Client.sayc                s   | j | tt| j| d S )N)r   r   r	  r   )r   r   r   )r   r   r   r   ^  s    
zClient.charc                s   | j | tt| j| d S )N)r   r   r	  r   )r   r   r   )r   r   r   r   b  s    
z
Client.keyc                s   | j | tt| j| d S )N)r   r   r	  r   )r   r   r   )r   r   r   r   f  s    
zClient.sound_icon)NN)r	   r
   r   r   r   r   r   r  r   r   r   r   r(   r   r   )r   r   r	  M  s   r	  c               @   s   e Zd ZdZdS )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.
    
    N)r	   r
   r   r   r   r   r   r   r  k  s   r  c               @   s   e Zd ZdZdZdZdS )ConnectionMethodzConstants describing the possible methods of connection to server.

    Retained for backwards compatibility but DEPRECATED. See CommunicationMethod.r6   r7   N)r	   r
   r   r   r8   r9   r   r   r   r   r    s   r  )r   r?   rW   r   r   ZtimeZtempfilerG   Zdummy_threading r   objectr   r*   r   r   r)   r1   r3   r4   r5   r:   r   ru   r   r   r   r   r	  r  r  r   r   r   r   <module>   s:   0. m!    u