
    qi&1                     d   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	e      Z G d
 de      Z G d dee      Z G d de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) zCLiveAvatar API.

API to communicate with LiveAvatar Streaming API.
    )Enum)AnyDictOptionalN)logger)	BaseModel)BaseAvatarApiStandardSessionResponsec                   H    e Zd ZU dZdZee   ed<   dZee   ed<   dZ	eed<   y)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        X/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/heygen/api_liveavatar.pyr   r      s/     #Hhsm" $J$Hcr   r   c                   0    e Zd ZU dZeed<   eed<   eed<   y)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   $   s     r   r   c                       e Zd ZdZdZdZy)VideoEncodingz%Enum representing the video encoding.H264VP8N)r   r   r   r   r"   r#   r   r   r   r!   r!   2   s    /D
Cr   r!   c                        e Zd ZdZdZdZdZdZy)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    <
CFDIr   r%   c                   >    e Zd ZU dZeed<   ej                  Zeed<   y)VideoSettingsz2Video encoding settings for session configuration.encodingqualityN)	r   r   r   r   r!   r   r%   r(   r-   r   r   r   r+   r+   B   s    <(--G\-r   r+   c                       e Zd ZU dZdZeed<   eed<    eej                        Z
ee   ed<   dZee   ed<   d	Zee   ed
<   d	Zee   ed<   y	)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   r1   r   r   r+   r!   r#   r3   r   r4   boolr5   r   r6   r   r   r   r   r/   r/   I   s_    	 D#N.;]EVEV.WNH]+W!&J&.2NH]+27;NH34;r   r/   c                   &    e Zd ZU dZeed<   eed<   y)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   r9   r9   ]   s     Or   r9   c                   0    e Zd ZU dZeed<   eed<   eed<   y)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   r9   r   r   r   r   r=   r=   i   s     I
Lr   r=   c                   N    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<   y)	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.
    r:   r   r   livekit_agent_tokenmax_session_durationws_urlN)r   r   r   r   r   r   rA   r   r   r   rC   rC   w   s+    	 OKr   rC   c                   0    e Zd ZU dZeed<   eed<   eed<   y)LiveAvatarSessionResponsezResponse model for LiveAvatar session start.

    Parameters:
        code (int): Response status code.
        data (LiveAvatarSessionData): Session data containing connection details.
        message (str): Response message.
    r>   r?   r@   N)r   r   r   r   rA   r   rC   r   r   r   r   rH   rH      s     I
Lr   rH   c                   4     e Zd ZdZdedededdf fdZ xZS )LiveAvatarApiErrorz+Custom exception for LiveAvatar API errors.r@   statusresponse_textreturnNc                 @    t         |   |       || _        || _        y)zInitialize the LiveAvatar API error.

        Args:
            message: Error message
            status: HTTP status code
            response_text: Raw response text from the API
        N)super__init__rK   rL   )selfr@   rK   rL   	__class__s       r   rP   zLiveAvatarApiError.__init__   s!     	!*r   )r   r   r   r   r   rA   rP   __classcell__)rR   s   @r   rJ   rJ      s,    5
+ 
+S 
+ 
+ 
+ 
+r   rJ   c                       e Zd ZdZdZdedej                  ddfdZ	 	 dded	ed
e	e
eef      de	e   def
dZdedefdZdedefdZdededefdZdedefdZdedefdZy)LiveAvatarApiz LiveAvatar Streaming API client.zhttps://api.liveavatar.com/v1api_keysessionrM   Nc                 .    || _         || _        d| _        y)zInitialize the LiveAvatar API.

        Args:
            api_key: LiveAvatar API key
            session: aiohttp client session
        N)_api_key_session_session_token)rQ   rV   rW   s      r   rP   zLiveAvatarApi.__init__   s      "r   methodpathparamsbearer_tokenc                   K   | j                    | }ddi}|r	d| |d<   n| j                  |d<   |d|d<   t        j                  d| d	|        	 | j                  j                  ||||
      4 d{   }|j                  sT|j                          d{   }t        j                  d|        t        d|j                   |j                  |      |j                          d{   cddd      d{    S 7 7 k7 7 # 1 d{  7  sw Y   yxY w# t        j                  $ r'}	t        j                  dt        |	               d}	~	ww xY 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_URLrY   r   debugrZ   requestoktexterrorrJ   rK   rd   aiohttpClientErrorr   )
rQ   r\   r]   r^   r_   urlre   responserL   es
             r   _requestzLiveAvatarApi._request   s`    , v&(
 )0'?GO$#'==GK &8GN#/xq>?	}},,VSvw,W 	- 	-[c{{*2--/$9MLL#9-!IJ,9(//9JK % 
 &]]_,	- 	- 	-$9 -	- 	- 	- 	- "" 	LLGAxPQ	s   AE#D" 7D8D" ; DDAD/D	0D3D" ?D D" ED" D	DD" DDDD" ED" "E5"EEErequest_datac                 .  K   |j                   |j                   nd|j                  d}|j                  m|j                  j                  |j                  j                  |j                  j
                  d}|j                         D ci c]  \  }}|	|| }}}||d<   |j                  |j                  |d<   |j                  G|j                  j                  j                  |j                  j                  j                  d}||d<   nd	t        j                  j                  i|d<   t        j                  d
|        | j!                  dd|       d{   }t        j                  d       t"        j%                  |      S c c}}w 7 4w)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.
        Nr0   )r1   r2   )r   r   r   r5   r4   )r,   r-   r3   r,   z/Creating LiveAvatar session token with params: POSTz/sessions/tokenz LiveAvatar session token created)r1   r2   r5   r   r   r   itemsr4   r3   r,   valuer-   r!   r#   r   rg   rq   r=   model_validate)rQ   rr   r^   r5   kvr3   ro   s           r   create_session_tokenz"LiveAvatarApi.create_session_token   s}     *6):):)FL%%F%//"
 &&2(77@@*99DD(77@@N 0>/C/C/EWtq!adWNW'5F#$"".#/#:#:F< &&2(77@@FF'66>>DDN (6F#$ )3M4E4E4K4K'LF#$FvhOPv/@&II79#228<<) X" Js%   B	F
FFCFF5Fr;   c                    K   | j                  dd|       d{   }t        j                  d       t        j	                  |      S 7 .w)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.
        rt   z/sessions/start)r_   NzLiveAvatar session started)rq   r   rg   rH   rw   )rQ   r;   ro   s      r   start_sessionzLiveAvatarApi.start_session  sD      v/@}]]13(77AA ^s   AA	/Ar:   c                 n   K   |st        d      d|i}| j                  dd||       d{   }|S 7 w)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.r:   rt   z/sessions/stop)r^   r_   N)
ValueErrorrq   )rQ   r:   r;   r^   ro   s        r   stop_sessionzLiveAvatarApi.stop_session-  sO      566
+$V- ' 
 
 
s   *535c                   K   | j                  |       d{   }|j                  j                  | _        | j	                  |j                  j                         d{   }t        |j                  j                  |j                  j                  |j                  j                  |j                  j                  |j                  j                  |      S 7 7 {w)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)r:   access_tokenr   rD   rF   raw_response)rz   r?   r;   r[   r|   r
   r:   r   r   rD   rF   )rQ   rr   token_responsesession_responses       r   new_sessionzLiveAvatarApi.new_sessionF  s       $88FF,11?? "&!3!3N4G4G4U4U!VV '',,77)..CC(--99 0 5 5 I I#((//)
 	
 G Ws#   CCACC A:CCc                    K   | j                   st        d      | j                  || j                          d{   S 7 w)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)r[   r~   r   )rQ   r:   s     r   close_sessionzLiveAvatarApi.close_sessiond  s<     , ""PQQ&&z43F3FGGGGs   7A >A )NN)r   r   r   r   rf   r   rl   ClientSessionrP   r   r   r   rq   r/   r=   rz   rH   r|   r   r
   r   r   r   r   r   rU   rU      s    *.H	# 	#g.C.C 	# 	# ,0&*22 2 c3h(	2
 sm2 
2h.=7.=	.=`B B9R B S   2
7
	 
<Hc Hc Hr   rU   )r   enumr   typingr   r   r   rl   logurur   pydanticr    pipecat.services.heygen.base_apir	   r
   r   r   r   r!   r%   r+   r/   r9   r=   rC   rH   	ExceptionrJ   rU   r   r   r   <module>r      s   
  & &    SI Y C 3 .I .<) <(	y 	9 I (	 + + THM THr   