o
    i&1                     @   s  d Z ddlmZ ddlmZmZmZ ddlZddlm	Z	 ddl
mZ ddlmZmZ G dd	 d	eZG d
d deZG dd deeZG dd de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 ) zCLiveAvatar API.

API to communicate with LiveAvatar Streaming API.
    )Enum)AnyDictOptionalN)logger)	BaseModel)BaseAvatarApiStandardSessionResponsec                   @   s>   e Zd ZU dZdZee ed< dZee ed< dZ	eed< dS )AvatarPersonaa   Avatar persona settings for LiveAvatar.

    Parameters:
        voice_id (Optional[str]): ID of the voice to be used.
        context_id (Optional[str]): Context ID for the avatar.
        language (str): Language code for the avatar (default: "en").
    Nvoice_id
context_idenlanguage)
__name__
__module____qualname____doc__r   r   str__annotations__r   r    r   r   Z/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/heygen/api_liveavatar.pyr
      s
   
 r
   c                   @   s*   e Zd ZU dZeed< eed< eed< dS )CustomSDKLiveKitConfigzCustom LiveKit configuration.

    Parameters:
        livekit_url (str): LiveKit server URL.
        livekit_room (str): LiveKit room name.
        livekit_client_token (str): LiveKit client access token.
    livekit_urllivekit_roomlivekit_client_tokenNr   r   r   r   r   r   r   r   r   r   r   $   
   
 r   c                   @   s   e Zd ZdZdZdZdS )VideoEncodingz%Enum representing the video encoding.H264VP8N)r   r   r   r   r   r   r   r   r   r   r   2   s    r   c                   @   s    e Zd ZdZdZdZdZdZdS )VideoQualityz2Enum representing different avatar quality levels.lowmediumhigh	very_highN)r   r   r   r   r!   r"   r#   r$   r   r   r   r   r    9   s    r    c                   @   s(   e Zd ZU dZeed< ejZeed< dS )VideoSettingsz2Video encoding settings for session configuration.encodingqualityN)	r   r   r   r   r   r   r    r#   r'   r   r   r   r   r%   B   s   
 r%   c                   @   sn   e Zd ZU dZdZeed< eed< eej	dZ
ee ed< dZee ed< d	Zee ed
< d	Zee ed< d	S )LiveAvatarNewSessionRequesta  Request model for creating a LiveAvatar session token.

    Parameters:
        mode (str): Session mode (default: "LITE").
        avatar_id (str): Unique identifier for the avatar.
        video_settings (VideoSettings): Video encoding settings.
        is_sandbox (bool): Enable sandbox mode (default: False).
        avatar_persona (AvatarPersona): Avatar persona configuration.
        livekit_config (CustomSDKLiveKitConfig): Custom LiveKit configuration.
    LITEmode	avatar_id)r&   video_settingsF
is_sandboxNavatar_personalivekit_config)r   r   r   r   r*   r   r   r%   r   r   r,   r   r-   boolr.   r
   r/   r   r   r   r   r   r(   I   s   
 r(   c                   @   s"   e Zd ZU dZeed< eed< dS )SessionTokenDatazData model for session token response.

    Parameters:
        session_id (str): Unique identifier for the session.
        session_token (str): Session token for authentication.
    
session_idsession_tokenNr   r   r   r   r   r1   ]   s   
 r1   c                   @   *   e Zd ZU dZeed< eed< eed< dS )SessionTokenResponsezResponse model for LiveAvatar session token.

    Parameters:
        code (int): Response status code.
        data (SessionTokenData): Session token data containing session_id and session_token.
        message (str): Response message.
    codedatamessageN)r   r   r   r   intr   r1   r   r   r   r   r   r5   i   r   r5   c                   @   sB   e Zd ZU dZeed< eed< eed< eed< eed< eed< dS )	LiveAvatarSessionDataa  Data model for LiveAvatar session response.

    Parameters:
        session_id (str): Unique identifier for the streaming session.
        livekit_url (str): LiveKit server URL for the session.
        livekit_client_token (str): Access token for LiveKit user.
        livekit_agent_token (str): Access token for LiveKit Agent (Pipecat).
        max_session_duration (int): Maximum session duration in seconds.
        ws_url (str): WebSocket URL for the session.
    r2   r   r   livekit_agent_tokenmax_session_durationws_urlN)r   r   r   r   r   r   r9   r   r   r   r   r:   w   s   
 r:   c                   @   r4   )LiveAvatarSessionResponsezResponse model for LiveAvatar session start.

    Parameters:
        code (int): Response status code.
        data (LiveAvatarSessionData): Session data containing connection details.
        message (str): Response message.
    r6   r7   r8   N)r   r   r   r   r9   r   r:   r   r   r   r   r   r>      r   r>   c                       s2   e Zd ZdZdedededdf fddZ  ZS )	LiveAvatarApiErrorz+Custom exception for LiveAvatar API errors.r8   statusresponse_textreturnNc                    s   t  | || _|| _dS )zInitialize the LiveAvatar API error.

        Args:
            message: Error message
            status: HTTP status code
            response_text: Raw response text from the API
        N)super__init__r@   rA   )selfr8   r@   rA   	__class__r   r   rD      s   
zLiveAvatarApiError.__init__)r   r   r   r   r   r9   rD   __classcell__r   r   rF   r   r?      s    &r?   c                   @   s   e Zd ZdZdZdedejddfddZ		dd	ed
ede	e
eef  de	e def
ddZdedefddZdedefddZdededefddZdedefddZdedefddZdS )LiveAvatarApiz LiveAvatar Streaming API client.zhttps://api.liveavatar.com/v1api_keysessionrB   Nc                 C   s   || _ || _d| _dS )zInitialize the LiveAvatar API.

        Args:
            api_key: LiveAvatar API key
            session: aiohttp client session
        N)_api_key_session_session_token)rE   rJ   rK   r   r   r   rD      s   
zLiveAvatarApi.__init__methodpathparamsbearer_tokenc           
   
      s&  | j  | }ddi}|rd| |d< n| j|d< |dur#d|d< td| d	|  zL| jj||||d
4 I dH 0}|js[| I dH }td|  t	d|j
 |j
|| I dH W  d  I dH  W S 1 I dH ssw   Y  W dS  tjy }	 ztdt|	   d}	~	ww )a  Make a request to the LiveAvatar API.

        Args:
            method: HTTP method (GET, POST, etc.).
            path: API endpoint path.
            params: JSON-serializable parameters.
            bearer_token: Optional bearer token for authorization.

        Returns:
            Parsed JSON response data.

        Raises:
            LiveAvatarApiError: If the API response is not successful.
            aiohttp.ClientError: For network-related errors.
        acceptzapplication/jsonzBearer authorizationz	X-API-KEYNzcontent-typezLiveAvatar API request:  )jsonheaderszLiveAvatar API error: zAPI request failed with status z,Network error while calling LiveAvatar API: )BASE_URLrL   r   debugrM   requestoktexterrorr?   r@   rV   aiohttpClientErrorr   )
rE   rO   rP   rQ   rR   urlrW   responserA   er   r   r   _request   s6   

4
zLiveAvatarApi._requestrequest_datac                    s   |j dur	|j nd|jd}|jdur-|jj|jj|jjd}dd | D }||d< |jdur7|j|d< |jdurL|jj	j
|jjj
d	}||d
< ndtjj
i|d
< td|  | dd|I dH }td t|S )a  Create a session token for LiveAvatar.

        https://docs.liveavatar.com/reference/create_session_token_v1_sessions_token_post

        Args:
            request_data: Session token configuration parameters.

        Returns:
            Session token information.
        Nr)   )r*   r+   )r   r   r   c                 S   s   i | ]\}}|d ur||qS )Nr   ).0kvr   r   r   
<dictcomp>  s    z6LiveAvatarApi.create_session_token.<locals>.<dictcomp>r.   r-   )r&   r'   r,   r&   z/Creating LiveAvatar session token with params: POSTz/sessions/tokenz LiveAvatar session token created)r*   r+   r.   r   r   r   itemsr-   r,   r&   valuer'   r   r   r   rY   rc   r5   model_validate)rE   rd   rQ   r.   r,   ra   r   r   r   create_session_token   s.   






z"LiveAvatarApi.create_session_tokenr3   c                    s,   | j dd|dI dH }td t|S )a-  Start a new LiveAvatar session.

        https://docs.liveavatar.com/reference/start_session_v1_sessions_start_post

        Args:
            session_token: Session token obtained from create_session_token.

        Returns:
            Session information including room URL and session ID.
        ri   z/sessions/start)rR   NzLiveAvatar session started)rc   r   rY   r>   rl   )rE   r3   ra   r   r   r   start_session  s   

zLiveAvatarApi.start_sessionr2   c                    s2   |st dd|i}| jdd||dI dH }|S )a  Stop an active LiveAvatar session.

        https://docs.liveavatar.com/reference/stop_session_v1_sessions_stop_post

        Args:
            session_id: ID of the session to stop.
            session_token: Session token for authentication.

        Returns:
            Response data from the stop session API call.

        Raises:
            ValueError: If session ID is not set.
        zSession ID is not set.r2   ri   z/sessions/stop)rQ   rR   N)
ValueErrorrc   )rE   r2   r3   rQ   ra   r   r   r   stop_session-  s   zLiveAvatarApi.stop_sessionc                    sX   |  |I dH }|jj| _| |jjI dH }t|jj|jj|jj|jj	|jj
|dS )aa  Create and start a new LiveAvatar session (convenience method).

        This combines create_session_token and start_session into a single call.

        Args:
            request_data: Session token configuration parameters.

        Returns:
            StandardSessionResponse: Standardized session information with LiveAvatar raw response.
        N)r2   access_tokenr   r;   r=   raw_response)rm   r7   r3   rN   rn   r	   r2   r   r   r;   r=   )rE   rd   token_responsesession_responser   r   r   new_sessionF  s   
zLiveAvatarApi.new_sessionc                    s$   | j std| || j I dH S )a  Close an active LiveAvatar session (convenience method).

        This is a convenience method that closes a session using the stored session token
        from the most recent `new_session()` call. It automatically uses the internally
        stored session token, eliminating the need to manually track tokens.

        Args:
            session_id: ID of the session to close.

        Returns:
            Response data from the stop session API call.

        Raises:
            ValueError: If no session token is available (i.e., `new_session()`
                       hasn't been called yet or the stored token is None).

        Note:
            This method requires that `new_session()` has been called previously to
            establish a stored session token. For more control over session tokens,
            use `stop_session()` directly with an explicit token parameter.
        z1Session token is not set. Call new_session first.N)rN   ro   rp   )rE   r2   r   r   r   close_sessiond  s   zLiveAvatarApi.close_session)NN)r   r   r   r   rX   r   r^   ClientSessionrD   r   r   r   rc   r(   r5   rm   r>   rn   rp   r	   ru   rv   r   r   r   r   rI      s<    
4
0
rI   )r   enumr   typingr   r   r   r^   logurur   pydanticr    pipecat.services.heygen.base_apir   r	   r
   r   r   r   r    r%   r(   r1   r5   r:   r>   	Exceptionr?   rI   r   r   r   r   <module>   s&   	