o
    i'                     @   s   d Z ddlmZ ddlmZmZmZmZ ddlZddl	m
Z
 ddlmZmZ ddlmZmZ G dd	 d	e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dS )z;HeyGen API.

API to communicate with HeyGen Streaming API.
    )Enum)AnyDictLiteralOptionalN)logger)	BaseModelField)BaseAvatarApiStandardSessionResponsec                   @   s   e Zd ZdZdZdZdZdS )AvatarQualityz2Enum representing different avatar quality levels.lowmediumhighN)__name__
__module____qualname____doc__r   r   r    r   r   b/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/heygen/api_interactive_avatar.pyr      s
    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      s    r   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )VoiceEmotionz0Enum representing different voice emotion types.excitedseriousfriendlysoothingbroadcasterN)	r   r   r   r   EXCITEDSERIOUSFRIENDLYSOOTHINGBROADCASTERr   r   r   r   r   %   s    r   c                   @   sb   e Zd ZU dZ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Zee ed< dS )ElevenLabsSettingsa  Settings for ElevenLabs voice configuration.

    Parameters:
        stability (Optional[float]): Stability of the voice synthesis.
        similarity_boost (Optional[float]): Adjustment for similarity in voice performance.
        model_id (Optional[str]): Identifier for the ElevenLabs model to use.
        style (Optional[int]): Style metric to apply for the voice.
        use_speaker_boost (Optional[bool]): Flag to enable speaker boost.
    N	stabilitysimilarity_boostmodel_idstyleuse_speaker_boost)r   r   r   r   r%   r   float__annotations__r&   r'   strr(   intr)   boolr   r   r   r   r$   /   s   
 
r$   c                   @   sb   e Zd ZU dZedddZee ed< dZ	ee
 ed< dZee ed< edddZee ed	< dS )
VoiceSettingsaV  Voice configuration settings.

    Parameters:
        voice_id (Optional[str]): ID of the voice to be used.
        rate (Optional[float]): Speaking rate for the voice.
        emotion (Optional[VoiceEmotion]): Emotion tone for the voice.
        elevenlabs_settings (Optional[ElevenLabsSettings]): Details for ElevenLabs configuration.
    NvoiceId)aliasvoice_idrateemotionelevenlabsSettingselevenlabs_settings)r   r   r   r   r	   r2   r   r,   r+   r3   r*   r4   r   r6   r$   r   r   r   r   r/   A   s   
 	r/   c                   @   s   e Zd ZU dZ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Zee	 ed< dZee	 ed< d	Zed	 ed
< dZee ed< dZee ed< dS )NewSessionRequesta  Requesting model for creating a new HeyGen session.

    Parameters:
        quality (Optional[AvatarQuality]): Desired quality of the avatar.
        avatar_id (Optional[str]): Unique identifier for the avatar.
        voice (Optional[VoiceSettings]): Voice configurations for the session.
        video_encoding (Optional[VideoEncoding]): Desired encoding for the video stream.
        knowledge_id (Optional[str]): Identifier for the knowledge base (if applicable).
        knowledge_base (Optional[str]): Details of any external knowledge base.
        version (Literal["v2"]): API version to use.
        disable_idle_timeout (Optional[bool]): Flag to disable automatic idle timeout.
        activity_idle_timeout (Optional[int]): Timeout in seconds for activity-based idle detection.
    Nquality	avatar_idvoicevideo_encodingknowledge_idknowledge_basev2versiondisable_idle_timeoutactivity_idle_timeout)r   r   r   r   r8   r   r   r+   r9   r,   r:   r/   r;   r   r<   r=   r?   r   r@   r.   rA   r-   r   r   r   r   r7   Q   s   
 r7   c                   @   s:   e Zd ZU dZeed< eed< eed< eed< eed< dS )HeyGenSessionu  Response model for a HeyGen session.

    Parameters:
        session_id (str): Unique identifier for the streaming session.
        access_token (str): Token for accessing the session securely.
        livekit_agent_token (str): Token for HeyGen’s audio agents(Pipecat).
        realtime_endpoint (str): Real-time communication endpoint URL.
        url (str): Direct URL for the session.
    
session_idaccess_tokenlivekit_agent_tokenrealtime_endpointurlN)r   r   r   r   r,   r+   r   r   r   r   rB   k   s   
 
rB   c                       s2   e Zd ZdZdedededdf fddZ  ZS )	HeygenApiErrorz'Custom exception for HeyGen API errors.messagestatusresponse_textreturnNc                    s   t  | || _|| _dS )zInitialize the HeyGen API error.

        Args:
            message: Error message
            status: HTTP status code
            response_text: Raw response text from the API
        N)super__init__rJ   rK   )selfrI   rJ   rK   	__class__r   r   rN      s   
zHeygenApiError.__init__)r   r   r   r   r,   r-   rN   __classcell__r   r   rP   r   rH   }   s    &rH   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	ee
f 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ede
fddZdefddZdS )	HeyGenApizHeyGen Streaming API client.zhttps://api.heygen.com/v1api_keysessionrL   Nc                 C   s   || _ || _dS )zInitialize the HeyGen API.

        Args:
            api_key: HeyGen API key
            session: Optional aiohttp client session
        N)rT   rU   )rO   rT   rU   r   r   r   rN      s   
zHeyGenApi.__init__Tpathparamsexpect_datac              
      s*  | j  | }| jdd}td|  zf| jj|||d4 I dH K}|jsB| I dH }td|  t	d|j
 |j
||r]| I dH }|d}	|	W  d  I dH  W S | I dH W  d  I dH  W S 1 I dH suw   Y  W dS  tjy }
 ztd	t|
   d}
~
ww )
a  Make a POST request to the HeyGen API.

        Args:
            path: API endpoint path.
            params: JSON-serializable parameters.
            expect_data: Whether to expect and extract 'data' field from response (default: True).

        Returns:
            Parsed JSON response data.

        Raises:
            HeygenApiError: If the API response is not successful or data is missing when expected.
            aiohttp.ClientError: For network-related errors.
        zapplication/json)z	x-api-keyzContent-TypezHeyGen API request: )jsonheadersNzHeyGen API error: zAPI request failed with status dataz(Network error while calling HeyGen API: )BASE_URLrT   r   debugrU   postoktexterrorrH   rJ   rY   getaiohttpClientErrorr,   )rO   rV   rW   rX   rG   rZ   responserK   	json_datar[   er   r   r   _request   s8   

4zHeyGenApi._requestrequest_datac              
      s   |j |j|jr|jjnd|jr|jjnd|jr|jjnd|jr$|jjndd|j|j|j	|j
|j|jd	}| d|I dH }td| t|}| |jI dH  t|j|j|j|j|j|dS )a5  Create a new streaming session and start it immediately.

        https://docs.heygen.com/reference/new-session

        Args:
            request_data: Session configuration parameters.

        Returns:
            StandardSessionResponse: Standardized session information with HeyGen raw response.
        N)r2   r3   r4   r6   )	r8   r9   r:   r<   r=   r?   r;   r@   rA   z/streaming.newzheygen session info)rC   rD   livekit_urlrE   ws_urlraw_response)r8   r9   r:   r0   r3   r4   r5   r<   r=   r?   r;   r@   rA   rh   printrB   model_validate_start_sessionrC   r   rD   rG   rE   rF   )rO   ri   rW   session_infoheygen_sessionr   r   r   new_session   s6   

zHeyGenApi.new_sessionrC   c                    s(   |st dd|i}| d|I dH S )a1  Start the streaming session.

        https://docs.heygen.com/reference/start-session

        Args:
            session_id: ID of the session to start.

        Returns:
            Response data from the start session API call.

        Raises:
            ValueError: If session ID is not set.
        .Session ID is not set. Call new_session first.rC   z/streaming.startN
ValueErrorrh   rO   rC   rW   r   r   r   ro      s   zHeyGenApi._start_sessionc                    s,   |st dd|i}| jd|ddI dH S )a=  Terminate an active the streaming session.

        https://docs.heygen.com/reference/close-session

        Args:
            session_id: ID of the session to stop.

        Returns:
            Response data from the stop session API call.

        Raises:
            ValueError: If session ID is not set.
        rs   rC   z/streaming.stopF)rX   Nrt   rv   r   r   r   close_session
  s   zHeyGenApi.close_sessionc                    s   |  di I dH }|d S )zCreate a streaming token.

        https://docs.heygen.com/reference/streaming-token

        Returns:
            str: The generated access token for the streaming session
        z/streaming.create_tokenNtoken)rh   )rO   
token_infor   r   r   create_token   s   zHeyGenApi.create_token)T)r   r   r   r   r\   r,   rc   ClientSessionrN   r   r   r.   rh   r7   r   rr   ro   rw   rz   r   r   r   r   rS      s    $
*.rS   )r   enumr   typingr   r   r   r   rc   logurur   pydanticr   r	    pipecat.services.heygen.base_apir
   r   r,   r   r   r   r$   r/   r7   rB   	ExceptionrH   rS   r   r   r   r   <module>   s    
