
    qi'                     ,   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	e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y)z;HeyGen API.

API to communicate with HeyGen Streaming API.
    )Enum)AnyDictLiteralOptionalN)logger)	BaseModelField)BaseAvatarApiStandardSessionResponsec                       e Zd ZdZdZdZdZy)AvatarQualityz2Enum representing different avatar quality levels.lowmediumhighN)__name__
__module____qualname____doc__r   r   r        `/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/heygen/api_interactive_avatar.pyr   r      s    <
CFDr   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      s    /D
Cr   r   c                   $    e Zd ZdZdZdZdZdZdZy)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    :GGHHKr   r   c                   v    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<   y)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*   /   sQ     "&Ix%(,huo,"Hhsm"E8C=(,x~,r   r*   c                       e Zd ZU dZ edd      Zee   ed<   dZ	ee
   ed<   dZee   ed<    edd      Zee   ed	<   y)
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
   r9   r   r2   r1   r:   r0   r;   r   r=   r*   r   r   r   r6   r6   A   sT     $D	:Hhsm: D(5/ &*GXl#*8=dJ^8_"45_r   r6   c                       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<   y)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   r@   r   r   r1   rA   r2   rB   r6   rC   r   rD   rE   rG   r   rH   r4   rI   r3   r   r   r   r?   r?   Q   s     (,GXm$+#Ix}#%)E8M").2NH]+2"&L(3-&$(NHSM(!GWT]!+/(4./+/8C=/r   r?   c                   D    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   y)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   r2   r1   r   r   r   rK   rK   k   s%     O	Hr   rK   c                   4     e Zd ZdZdedededdf fdZ xZS )HeygenApiErrorz'Custom exception for HeyGen API errors.messagestatusresponse_textreturnNc                 @    t         |   |       || _        || _        y)zInitialize the HeyGen API error.

        Args:
            message: Error message
            status: HTTP status code
            response_text: Raw response text from the API
        N)super__init__rT   rU   )selfrS   rT   rU   	__class__s       r   rY   zHeygenApiError.__init__   s!     	!*r   )r   r   r   r   r2   r3   rY   __classcell__)r[   s   @r   rR   rR   }   s,    1
+ 
+S 
+ 
+ 
+ 
+r   rR   c            	           e Zd ZdZdZdedej                  ddfdZdded	e	ee
f   d
ede
fdZdedefdZdede
fdZdede
fdZdefdZy)	HeyGenApizHeyGen Streaming API client.zhttps://api.heygen.com/v1api_keysessionrV   Nc                      || _         || _        y)zInitialize the HeyGen API.

        Args:
            api_key: HeyGen API key
            session: Optional aiohttp client session
        N)r_   r`   )rZ   r_   r`   s      r   rY   zHeyGenApi.__init__   s     r   pathparamsexpect_datac                   K   | j                    | }| j                  dd}t        j                  d|        	 | j                  j                  |||      4 d{   }|j                  sT|j                          d{   }t        j                  d|        t        d|j                   |j                  |      |r<|j                          d{   }|j                  d      }	|	cddd      d{    S |j                          d{   cddd      d{    S 7 7 7 U7 47 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 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_URLr_   r   debugr`   postoktexterrorrR   rT   rf   getaiohttpClientErrorr2   )rZ   rb   rc   rd   rP   rg   responserU   	json_datarh   es              r   _requestzHeyGenApi._request   sh     v&.

 	+C512	||((67(K - -x{{*2--/$9MLL#5m_!EF(9(//9JK % 
 &.mmo 5I$==0D- - - &]]_,- - -$9 !6- -- - - - "" 	LLCCF8LM	s   8F"E
 D)E
 ! D5D+AD5D-D5.E
 :D/;E
 ?F D5D1D5E
 #D3$E
 (F)E
 +D5-D5/E
 1D53E
 5E;D><EE
 FE
 
F"E??FFrequest_datac           
      &  K   |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	}| j                  d|       d{   }t        d|       t        j!                  |      }| j#                  |j$                         d{    t'        |j$                  |j(                  |j*                  |j,                  |j.                  |      S 7 7 Iw)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)r9   r:   r;   r=   )	r@   rA   rB   rD   rE   rG   rC   rH   rI   z/streaming.newzheygen session info)rL   rM   livekit_urlrN   ws_urlraw_response)r@   rA   rB   r7   r:   r;   r<   rD   rE   rG   rC   rH   rI   ru   printrK   model_validate_start_sessionrL   r   rM   rP   rN   rO   )rZ   rv   rc   session_infoheygen_sessions        r   new_sessionzHeyGenApi.new_session   s[     $++%//:F:L:LL..66RV3?3E3E**//49E9K9K<--55QU=I=O=OL&&99UY )55*99#++*99$0$E$E%1%G%G!
$ "]]+;VDD#\2&55lC!!.";";<<< '%00'44&** . B B!33'
 	
 E
 	=s&   C?FFAFFAFFrL   c                 d   K   |st        d      d|i}| j                  d|       d{   S 7 w)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.rL   z/streaming.startN
ValueErrorru   rZ   rL   rc   s      r   r}   zHeyGenApi._start_session   s?      MNN *
 ]]#5v>>>>s   '0.0c                 h   K   |st        d      d|i}| j                  d|d       d{   S 7 w)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.
        r   rL   z/streaming.stopF)rd   Nr   r   s      r   close_sessionzHeyGenApi.close_session
  sC      MNN *
 ]]#4f%]PPPPs   )202c                 L   K   | j                  di        d{   }|d   S 7 	w)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)ru   )rZ   
token_infos     r   create_tokenzHeyGenApi.create_token   s-       ==)BBGG
'"" Hs   $"
$)T)r   r   r   r   ri   r2   rp   ClientSessionrY   r   r   r4   ru   r?   r   r   r}   r   r   r   r   r   r^   r^      s    &*H g.C.C  (3 (S#X (T (]` (T,
.? ,
D[ ,
\?s ?s ?,Qc Qc Q,	#C 	#r   r^   )r   enumr   typingr   r   r   r   rp   logurur   pydanticr	   r
    pipecat.services.heygen.base_apir   r   r2   r   r   r   r*   r6   r?   rK   	ExceptionrR   r^   r   r   r   <module>r      s   
  / /   % SC C  3  - -$`I ` 0	 04I $+Y + \# \#r   