
    iW$                     X   d Z ddlZddlZddlZddlZddlmZmZmZm	Z	 ddl
Z
ddlZddlmZ  G d d      Z e       Zedk(  rhddlZ ed        ed	        ed
       ej%                         r	 ed       n ed        ed       d Z ej*                   e               ed       yy)ze
Genesis Talking Website Widget - Voice Handler
Telnyx integration for voice conversations (TTS/STT)
    N)DictAnyOptionalTuple)datetimec                       e Zd ZdZd ZdedefdZ	 ddeded	ee   defd
Zdede	ee
f   de	ee
f   deee	ee
f   f   fdZdede	ee
f   dee	eef      fdZdefdZy)VoiceHandlerz7Handler for Telnyx voice operations (TTS, STT, WebRTC).c                     t        j                  dd      | _        t        j                  dd      | _        t        j                  dd      | _        | j                  t
        _        y )NTELNYX_API_KEY:KEY019BE7A3A2D749FCA8681CFF8448A7F0_vTMM1n77CtQxLDT2ra3P1zTELNYX_VOICE
eucalyptusTELNYX_MODELzgoogle/gemini-2.5-flash)osgetenvapi_keyvoicemodeltelnyx)selfs    9/mnt/e/genesis-system/RECEPTIONISTAI/api/voice_handler.py__init__zVoiceHandler.__init__   sF    yy!13opYY~|<
YY~/HI
    audio_base64returnc                    K   	 t        j                  |      }d}|S # t        $ r}t        d|        Y d}~yd}~ww xY ww)z
        Convert audio to text using Telnyx STT.

        Args:
            audio_base64: Base64 encoded audio (WAV/MP3)

        Returns:
            Transcribed text
        z7[STT_PLACEHOLDER] User speech would be transcribed herezVoice input processing error: N )base64	b64decode	Exceptionprint)r   r   audio_bytestranscriptiones        r   process_voice_inputz VoiceHandler.process_voice_input   sK     	 **<8K VM   	21#67	s$   A A	>9A>ANtextbusiness_id
voice_namec                 n  K   	 |xs | j                   }d}d| j                   dd}d| |dd}t        j                         4 d{   }|j	                  |||d	
       d{   }	|	j
                  dk(  rC|	j                  }
t        j                  |
      j                  d      }|cddd      d{    S t        d|	j
                   d|	j                          	 ddd      d{    y7 7 7 @7 # 1 d{  7  sw Y   yxY w# t        $ r}t        d|        Y d}~yd}~ww xY ww)a"  
        Convert text to speech using Telnyx TTS.

        Args:
            text: Text to convert to speech
            business_id: Business identifier
            voice_name: Optional custom voice (defaults to eucalyptus)

        Returns:
            Base64 encoded audio (WAV)
        z(https://api.telnyx.com/v2/text-to-speechBearer zapplication/json)AuthorizationzContent-TypezTelnyx.NaturalHD.wav)r   r&   output_formatNg      >@)jsonheaderstimeout   zutf-8zTTS API error: z - r   zVoice generation error: )r   r   httpxAsyncClientpoststatus_codecontentr   	b64encodedecoder!   r&   r    )r   r&   r'   r(   r   urlr/   payloadclientresponser"   r   r$   s                r   generate_voice_responsez$VoiceHandler.generate_voice_response6   sC    "	 ,$**E<C#*4<<.!9 2G
 -UG4!&G ((*  f!'SwY]!^^''3."*"2"2K#)#3#3K#@#G#G#PL'   OH,@,@+AX]]OTU  ^      	,QC01	s   D5AD 	C4
D C<&C6'AC<+D 7C88D <D5=&C<#D .C:/D 3D54D 6C<8D :D <DDD
D D5D 	D2D-(D5-D22D5visitor_messagebusiness_contextsession_contextc                   K   	 |j                  dd      }|j                  dd      }|j                         t        fddD              rd}nlt        fdd	D              rd
}d|d<   d|d<   nKt        fddD              rd}d|d<   d|d<   n*t        fddD              r
d| d| d}nd}d|d<   d|d<   ||d<   ||d<   |j                  dd      dz   |d<   ||fS # t        $ r}t	        d|        d |fcY d!}~S d!}~ww xY ww)"a9  
        Generate AI response using Gemini or other LLM.

        Args:
            visitor_message: What the visitor said/typed
            business_context: Business knowledge base
            session_context: Current session state

        Returns:
            (response_text, updated_session_context)
        namezour business
agent_nameSarahc              3   &   K   | ]  }|v  
 y wN .0wordmessage_lowers     r   	<genexpr>z4VoiceHandler.generate_ai_response.<locals>.<genexpr>   s     PT4=(P   )hoursopenclosezCWe're open Monday to Friday, 9 AM to 5 PM. How else can I help you?c              3   &   K   | ]  }|v  
 y wrF   rG   rH   s     r   rL   z4VoiceHandler.generate_ai_response.<locals>.<genexpr>   s     UtT]*UrM   )pricecostzhow muchzpI'd be happy to discuss pricing with you. Can I get your name and phone number so one of our team can follow up?pricing_inquiryintentTlead_capture_readyc              3   &   K   | ]  }|v  
 y wrF   rG   rH   s     r   rL   z4VoiceHandler.generate_ai_response.<locals>.<genexpr>   s     [tT]*[rM   )bookappointmentschedulezFI can help you book an appointment! What's your name and phone number?bookingc              3   &   K   | ]  }|v  
 y wrF   rG   rH   s     r   rL   z4VoiceHandler.generate_ai_response.<locals>.<genexpr>   s     NtT]*NrM   )hihelloheyzHi there! I'm z, the virtual assistant for z. How can I help you today?zhThanks for your message. Let me connect you with the right person. Can I get your name and phone number?general_inquirylast_messagelast_responsemessage_countr      zAI response generation error: z]I'm having trouble processing that. Can I get your phone number so someone can call you back?N)getloweranyr    r!   )	r   r>   r?   r@   business_namerC   r<   r$   rK   s	           @r   generate_ai_responsez!VoiceHandler.generate_ai_responseh   sf    "'	D -00HM)--lGDJ ,113MP5OPP`U7TUU N,=)8< 45[7Z[[c,5)8< 45N7MNN+J<7STaSbb}~ F,=)8< 45 />ON+/7OO,/>/B/B?TU/VYZ/ZOO,_,, 	D21#67r  uD  D  D	Ds5   D
CC" !D
"	D+D<D=D
DD
messagec                 x  K   ddl }i }g d}|D ],  }|j                  ||      }|s|j                  d      |d<    n |j                  d|      }|r|j                  d      |d<   ddg}	|	D ]E  }|j                  |||j                        }|s#|j                  d	      j	                         |d
<    n |r|S dS w)z
        Extract lead information from visitor message.

        Args:
            message: Visitor's message
            session_context: Current session state

        Returns:
            Dict with name, phone, email if detected
        r   N)z\b0[2-478]\d{8}\bz"\b\+61\s?[2-478]\s?\d{4}\s?\d{4}\bz\b\d{4}\s?\d{3}\s?\d{3}\bphonez3\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\bemailzB(?:my name is|i'm|i am|this is)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)z7^([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)(?:\s+here|\s+calling)rd   rB   )researchgroup
IGNORECASEstrip)
r   rj   r@   rn   	lead_infophone_patternspatternmatchemail_matchname_patternss
             r   detect_lead_infozVoiceHandler.detect_lead_info   s      		
 & 	GIIgw/E%*[[^	'"		 ii VX_`!,!2!21!5Ig RF

 % 	GIIgw>E$)KKN$8$8$:	&!		 &y/4/s   $B:A'B:+B:c                     	 d}dd| j                    i}ddl}|j                  ||d      }|j                  dk(  S # t        $ r}t        d	|        Y d}~y
d}~ww xY w)zTest Telnyx API connectivity.z/https://api.telnyx.com/v2/text-to-speech/voicesr+   r*   r   N
   )r/   r0   r1   zTelnyx connection failed: F)r   requestsre   r5   r    r!   )r   r9   r/   r|   r<   r$   s         r   test_connectionzVoiceHandler.test_connection   sl    
	CC&'$,,(@AG||C"|EH''3.. 	.qc23	s   9< 	AAArF   )__name__
__module____qualname____doc__r   strr%   r   r=   r   r   r   ri   ry   boolr}   rG   r   r   r	   r	      s    A&c c B %)	00 0 SM	0
 
0d8D8D sCx.8D c3h	8D
 
sDcN"	#8Dt1010 c3h10 
$sCx.	!	10f r   r	   __main__z'Genesis Widget API - Voice Handler Testz<============================================================z Testing Telnyx API connection...u   ✅ Connected to Telnyxu   ❌ Connection failedrd   c                     K   t        d       d} t        j                  | d       d {   }|rt        dt        |       d       y t        d       y 7 +w)Nz
Testing Text-to-Speech...zQHi! This is Sarah from ReceptionistAI. This is a test of the Telnyx voice system.test_businessu   ✅ Generated z bytes of audio (base64)u0   ⚠️  TTS returned empty (check API key/quota))r!   voice_handlerr=   len)r&   r   s     r   test_ttsr      sS     +,b*BB4YYN3|#4"55MNODE	 Zs   'AA,Au   
🎙️ Voice handler ready)r   r   r   iotempfiletypingr   r   r   r   r   r2   r   r	   r   r~   asyncior!   r}   exitr   runrG   r   r   <module>r      s   
 
  	  - -   Q Qj  z	
34	(O 

,-$$&'(%&QF GKK
	
)*5 r   