o
    y	i+!                     @   sV   d Z ddlmZmZmZ ddlmZ ddlmZ ddl	m
Z
 G dd dZei ZdS )	zf
ElevenLabs + Nova Lite Service Wrapper
Combines Nova Lite LLM with ElevenLabs TTS for service_type 3
    )OptionalDictAny)Log)NovaliteBedrockService)ElevenLabsTTSServicec                
   @   s   e Zd ZdZdeeef fddZddededed	e	e fd
dZ
ded	efddZded	e	e fddZd	efddZded	efddZd	eeef fddZd	efddZdS )ElevenLabsNovaServicez
    Service wrapper combining Nova Lite LLM with ElevenLabs TTS.
    Provides emotional expressions and high-quality voice synthesis.
    
bot_configc                 C   sF   || _ |r|ddnd}t | _t|d| _td|pd  dS )z
        Initialize the ElevenLabs + Nova Lite service.
        
        Args:
            bot_config: Bot configuration dictionary
        Z
voice_typeN)voice_idu9   🤖 ElevenLabs + Nova Lite service initialized - Voice: default)r	   getr   novalite_servicer   elevenlabs_ttsr   info)selfr	   r
    r   #services/elevenlabs_nova_service.py__init__   s
   zElevenLabsNovaService.__init__N
user_inputsystem_promptconversation_historyreturnc              
      s   z9t d|dd  d | jj|||dI dH }|r3| j|}t d|dd  d |W S t d W dS  tyU } zt d|  W Y d}~dS d}~ww )	aG  
        Generate text response using Nova Lite LLM.
        
        Args:
            user_input: User's input text
            system_prompt: System prompt for the LLM
            conversation_history: Previous conversation context
            
        Returns:
            Generated response text or None if failed
        u(   🤖 Generating Nova Lite response for: N2   ...)r   r   r   u0   ✅ Nova Lite response generated with emotions: u(   ❌ Nova Lite response generation failedu)   ❌ Error generating Nova Lite response: )	r   debugr   generate_responser   Zadd_emotional_tagsr   error	Exception)r   r   r   r   ZresponseZemotional_responseer   r   r   r   $   s&   
z'ElevenLabsNovaService.generate_responsetextc                 C   s(   ddl }d}|j|d||jd}| S )z
        Remove emotion labels from text so they are not spoken.
        
        Args:
            text: Text with emotion labels
            
        Returns:
            Text without emotion labels
        r   NzU\[(?:excited|friendly|professional|sad|confident|surprised|calm|laughs|whispers)\]\s* )flags)resub
IGNORECASEstrip)r   r   r"   Zemotion_patterncleaned_textr   r   r   _remove_emotion_labelsG   s   
z,ElevenLabsNovaService._remove_emotion_labelsc              
      s   zIt d|dd  d | |}| |}t d| d|dd  d | j||I dH }|rCt dt| d |W S t d	 W dS  t	ye } zt d
|  W Y d}~dS d}~ww )a  
        Convert text to speech using ElevenLabs TTS with emotional expressions.
        
        Args:
            text: Text to convert (should already include emotional tags)
            
        Returns:
            Audio bytes in MP3 format or None if failed
        u0   🎤 Converting text to speech with ElevenLabs: Nr   r   u9   🎤 Converting text to speech with ElevenLabs (emotion: z): u+   ✅ ElevenLabs TTS conversion successful - z bytesu$   ❌ ElevenLabs TTS conversion failedu3   ❌ Error in ElevenLabs text-to-speech conversion: )
r   r   _detect_emotion_from_textr'   r   text_to_speechr   lenr   r   )r   r   Zemotionr&   Z
audio_datar   r   r   r   r)   [   s"   


 
z$ElevenLabsNovaService.text_to_speechc                    s   t d dS )z
        Handle conversation interruption.
        Note: This is handled at the call session level, not here.
        
        Returns:
            True (interruption handled)
        u;   🛑 Interruption handled by ElevenLabs + Nova Lite serviceT)r   r   r   r   r   r   handle_interruption~   s   
z)ElevenLabsNovaService.handle_interruptionc                    s  |   d v sd v rdS d v sd v rdS d v rdS d	 v r$d
S d v r*dS t fdddD r7dS t fdddD rDdS t fdddD rQdS t fdddD r^d
S t fdddD rkdS t fdddD rxdS t fdddD rdS dS )z
        Detect emotion from text content for voice settings optimization.
        
        Args:
            text: Text to analyze
            
        Returns:
            Emotion type string
        z	[excited]z[laughs]Zexcitedz[sad]z
[whispers]Zsadz[confident]Z	confidentz[surprised]Z	surprisedz[calm]Zcalmc                 3       | ]}| v V  qd S Nr   .0ZwordZ
text_lowerr   r   	<genexpr>       zBElevenLabsNovaService._detect_emotion_from_text.<locals>.<genexpr>)ZgreatZ	excellentZ	wonderfulZamazingZ	fantasticc                 3   r-   r.   r   r/   r1   r   r   r2      r3   )ZsorryZunfortunatelyZregretZ	apologizec                 3   r-   r.   r   r/   r1   r   r   r2      r3   )ZsureZ
definitelyZ
absolutelyZ	certainlyc                 3   r-   r.   r   r/   r1   r   r   r2      r3   )ZwowZreallyZ
incredibleZunbelievablec                 3   r-   r.   r   r/   r1   r   r   r2      r3   )ZokayZalrightz
no problemc                 3   r-   r.   r   r/   r1   r   r   r2      r3   )Zhellohizgood morningzgood afternoonzgood eveningZwelcomeZfriendlyc                 3   r-   r.   r   r/   r1   r   r   r2      r3   )zaccording toZ
documentedZestablishedZ	procedureZprotocolZstandardZprofessionalr   )lowerany)r   r   r   r1   r   r(      s4   
z/ElevenLabsNovaService._detect_emotion_from_textc                 C   s    d| j  | j dddddS )zt
        Get service information.
        
        Returns:
            Dictionary with service information
        Zelevenlabs_novaTz1-3 secondsZhigh)Zservice_typeZllm_serviceZtts_serviceZsupports_interruptionZsupports_emotionsZlatencyZvoice_quality)r   Zget_model_infor   get_service_infor+   r   r   r   r7      s   z&ElevenLabsNovaService.get_service_infoc              
      s   z,| j  I dH }|std W dS | j I dH }|s&td W dS td W dS  tyH } ztd|  W Y d}~dS d}~ww )z
        Test both Nova Lite and ElevenLabs services.
        
        Returns:
            True if both services are working, False otherwise
        Nu!   ❌ Nova Lite service test failedFu&   ❌ ElevenLabs TTS service test failedu6   ✅ Both Nova Lite and ElevenLabs services are workingTu3   ❌ Error testing ElevenLabs + Nova Lite services: )r   Ztest_connectionr   r   r   r   r   )r   Z	nova_testZelevenlabs_testr   r   r   r   test_services   s"   


z#ElevenLabsNovaService.test_servicesr.   )__name__
__module____qualname____doc__r   strr   r   listr   r   r'   bytesr)   boolr,   r(   r7   r8   r   r   r   r   r      s     ##*r   N)r<   typingr   r   r   Zservices.log_utilsr   Z!services.novalite_bedrock_servicer   Zservices.elevenlabs_tts_servicer   r   Zelevenlabs_nova_servicer   r   r   r   <module>   s     V