
    qiu                        d Z ddlZddlmZmZmZ ddlmZmZm	Z	 ddl
mZ ddlmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZmZmZmZmZ dd	lm Z  dd
l!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( 	 ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0  G d d      Z5e G d de             Z6 G d de"      Z7y# e1$ r7Z2 ejf                  de2         ejf                  d        e4de2       dZ2[2ww xY w)z/Deepgram speech-to-text service implementation.    N)	dataclassfieldfields)AnyAsyncGeneratorOptional)logger)
CancelFrameEndFrameFrameInterimTranscriptionFrame
StartFrameTranscriptionFrameUserStartedSpeakingFrameUserStoppedSpeakingFrameVADUserStartedSpeakingFrameVADUserStoppedSpeakingFrame)FrameDirection)	NOT_GIVENSTTSettings	_NotGiven_warn_deprecated_paramis_given)DEEPGRAM_TTFS_P99)
STTService)Language)time_now_iso8601)
traced_stt)AsyncDeepgramClient)	EventType)ListenV1ResultsListenV1SpeechStartedListenV1UtteranceEndzException: zIIn order to use Deepgram, you need to `pip install pipecat-ai[deepgram]`.zMissing module: c            :          e Zd ZdZddddddddddddddddddddddddddddddee   dee   dee   dee   dee   d	ee   d
ee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   dee   f8d Z	d!efd"Z
d#efd$Zy)%LiveOptionsaG  Deepgram live transcription options.

    Compatibility wrapper that mirrors the ``LiveOptions`` class removed in
    deepgram-sdk v6.

    .. deprecated:: 0.0.105
        Use ``settings=DeepgramSTTSettings(...)`` for runtime-updatable fields
        and direct ``__init__`` parameters for connection-level config instead.
    N)callbackcallback_methodchannelsdetect_entitiesdiarize	dictationencodingendpointingextrainterim_resultskeytermkeywordslanguagemip_opt_outmodelmultichannelnumeralsprofanity_filter	punctuateredactreplacesample_ratesearchsmart_formattagutterance_end_ms
vad_eventsversionr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   c                   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        y)a  Initialize live transcription options.

        Args:
            callback: Callback URL for async transcription delivery.
            callback_method: HTTP method to use for the callback (``"GET"`` or ``"POST"``).
            channels: Number of audio channels.
            detect_entities: Enable named entity detection.
            diarize: Enable speaker diarization.
            dictation: Enable dictation mode (converts commands to punctuation).
            encoding: Audio encoding (e.g. ``"linear16"``).
            endpointing: Endpointing sensitivity in ms, or ``False`` to disable.
            extra: Additional key-value metadata to attach to the transcription (str or list).
            interim_results: Whether to emit interim transcriptions.
            keyterm: Keyterms to boost (str or list of str).
            keywords: Keywords to boost (str or list of str).
            language: BCP-47 language tag (e.g. ``"en-US"``).
            mip_opt_out: Opt out of model improvement program.
            model: Deepgram model name (e.g. ``"nova-3-general"``).
            multichannel: Enable per-channel transcription for multi-channel audio.
            numerals: Convert spoken numbers to numerals.
            profanity_filter: Filter profanity from transcripts.
            punctuate: Add punctuation to transcripts.
            redact: Redact sensitive information (str or list of redaction types).
            replace: Word replacement rules (str or list).
            sample_rate: Audio sample rate in Hz.
            search: Search terms to highlight (str or list of str).
            smart_format: Apply smart formatting to transcripts.
            tag: Custom billing tag (str or list of str).
            utterance_end_ms: Silence duration in ms before an utterance-end event.
            vad_events: Enable Deepgram VAD speech-started / utterance-end events.
            version: Model version (e.g. ``"latest"``).
            **kwargs: Any additional Deepgram query parameters.
        N)r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   _extra)selfr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   kwargss                                 O/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/deepgram/stt.py__init__zLiveOptions.__init__B   s    D !. ." &
.  &
(  0"&( 0$    namec                 ~    | j                   j                  di       }	 ||   S # t        $ r t        d| d      w xY w)NrC   z''LiveOptions' object has no attribute '')__dict__getKeyErrorAttributeError)rD   rI   r.   s      rF   __getattr__zLiveOptions.__getattr__   sQ     !!(B/	T; 	T #J4&PQ!RSS	Ts   # <returnc                     t        |       j                         D ci c]  \  }}|j                  d      r||| }}}|j                  | j                  j                         D ci c]  \  }}|	|| c}}       |S c c}}w c c}}w )z&Return a dict of all non-None options._)varsitems
startswithupdaterC   )rD   kvresults       rF   to_dictzLiveOptions.to_dict   sy    #':#3#3#5a41aQ\\#=NSTS`!Q$aa(9(9(;M1q}q!tMN bMs   BBB*
B

5B

)__name__
__module____qualname____doc__r   strintboolr   rG   rP   dictr[    rH   rF   r%   r%   7   s"    #')-"&*."&$("&%)#*.!%"&"&&*#'+#'+/$( $!%%) $'+!*.%)!%=^ 3-^ "#	^
 3-^ "$^ $^ D>^ 3-^ c]^ }^ "$^ #^ 3-^ 3-^  d^!^" }#^$ tn%^& 4.'^( #4.)^* D>+^, -^. #/^0 c]1^2 3^4 tn5^6 c]7^8 #3-9^: TN;^< #=^@T T rH   r%   c                   `   e Zd ZU dZ ed       Zeez  ed<    ed       Z	eez  ed<    ed       Z
eez  ed<    ed	       Zeez  ed
<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zed z  ez  ed!<    ed"       Zeez  ed#<   d%d$Zy )&DeepgramSTTSettingsa  Settings for DeepgramSTTService.

    ``model`` and ``language`` are inherited from ``STTSettings`` /
    ``ServiceSettings``.  Additional Deepgram connection params may
    be passed in through ``extra`` (also inherited).

    Parameters:
        detect_entities: Enable named entity detection.
        diarize: Enable speaker diarization.
        dictation: Enable dictation mode (converts commands to punctuation).
        endpointing: Endpointing sensitivity in ms, or ``False`` to disable.
        interim_results: Whether to emit interim transcriptions.
        keyterm: Keyterms to boost (str or list of str).
        keywords: Keywords to boost (str or list of str).
        numerals: Convert spoken numbers to numerals.
        profanity_filter: Filter profanity from transcripts.
        punctuate: Add punctuation to transcripts.
        redact: Redact sensitive information (str or list of redaction types).
        replace: Word replacement rules (str or list).
        search: Search terms to highlight (str or list of str).
        smart_format: Apply smart formatting to transcripts.
        utterance_end_ms: Silence duration in ms before an utterance-end event.
        vad_events: Enable Deepgram VAD speech-started / utterance-end events.
    c                      t         S Nr   rd   rH   rF   <lambda>zDeepgramSTTSettings.<lambda>       i rH   )default_factoryr)   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>       i rH   r*   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>       	 rH   r+   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>        rH   r-   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   rk   rH   r/   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>       Y rH   r0   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   rn   rH   r1   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   s    y rH   r6   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   s    y rH   r7   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   rp   rH   r8   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>       I rH   r9   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   ru   rH   r:   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   r{   rH   r<   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   s    9 rH   r=   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   s    Y rH   Nr?   c                      t         S rh   ri   rd   rH   rF   rj   zDeepgramSTTSettings.<lambda>   rr   rH   r@   c                    | j                   syt        |       D ch c]7  }|j                  dvr'|j                  j                  d      s|j                  9 }}t	        | j                   j                               D ]E  }||v st        | |      }t        |      st        | || j                   |          | j                   |= G yc c}w )a  Sync values from extra dict to declared fields.

        If a key in extra matches a field name and the field is NOT_GIVEN,
        promote the extra value to the field. This ensures self._settings
        always reflects the "final truth" of values that will be used.

        Keys in extra that match declared fields are always removed from extra
        to avoid confusion, even if the field was already set.
        N)r.   r4   r2   rS   )	r.   r   rI   rV   listkeysgetattrr   setattr)rD   ffield_nameskeycurrent_values        rF   _sync_extra_to_fieldsz)DeepgramSTTSettings._sync_extra_to_fields   s     zz D\
vv;;AFFDUDUVYDZ FF
 
 

)* 	$Ck! 'c 2.D#tzz#7JJsO	$
s   <C)rQ   N)r\   r]   r^   r_   r   r)   rb   r   __annotations__r*   r+   r-   r   r/   r0   r1   r6   r7   r8   r9   r:   r<   r=   r?   ra   r@   r   rd   rH   rF   rf   rf      s^   2 ).>O(POTI%P %6G HGTIH"'8I"JItiJ#(9J#KKyK(->O(POTI%P$5FGGS9_G %6G HHcIoH!&7H!IHdYI).?P)QdY&Q"'8I"JItiJ#4EFFC)OF$5FGGS9_G#4EFFC)OF%*;L%ML$"M/4EV/WcDj9,W#(9J#KJy K$rH   rf   c            "           e Zd ZU dZeZeed<   dddddddddddddded	d
edededede	de
dee	   dee   dee   dee   dee
   dee   dee   de
dee   dee   f  fdZed        Zde
fdZdedeeef   f fdZd ef fd!Zd ef fd"Zd ef fd#Zd$edeedf   fd%Zdefd&Z d' Z!d( Z"d) Z#d* Z$d+ Z%d, Z&d- Z'd. Z(e)	 d6d/ed0e
d1ee*   fd2       Z+d3 Z,d ed4e-f fd5Z. xZ/S )7DeepgramSTTServicea  Deepgram speech-to-text service.

    Provides real-time speech recognition using Deepgram's WebSocket API.
    Supports configurable models, languages, and various audio processing options.

    Event handlers available (in addition to STTService events):

    - on_speech_started(service): Deepgram detected start of speech
    - on_utterance_end(service): Deepgram detected end of utterance

    Example::

        @stt.event_handler("on_speech_started")
        async def on_speech_started(service):
            ...
    	_settings linear16   FNT)urlbase_urlr,   r(   r5   r;   r&   r'   r>   r3   live_optionsaddonsshould_interruptsettingsttfs_p99_latencyapi_keyr   r   r,   r(   r5   r;   r&   r'   r>   r3   r   r   r   r   r   c                :   |rFddl }|j                         5  |j                  d       |j                  dt               ddd       |}t        d)i dddt        j                  dd	d
d	dd	dddddddddd	dddddddddddd	dddd	}|5t        dt
               |s"|j                  ||j                  }|j                  |j                  }|j                  |j                  }|j                  |j                  }|j                  |j                  }	|j                  |j                  }
|j                  |j                  }|j                   |j                   }h d}|j#                         j%                         D ci c]  \  }}||vs|| }}}t
        j'                  |      }|j)                  |       ||j)                  |       |j+                          t-        | \  d)|||d| || _        || _        || _        || _        || _        || _        |	| _        |
| _        || _         | jB                  jD                  rFddl }|j                         5  |j                  d       |j                  dt        d       ddd       |rU	 dd l#m$} |jK                  d!      r|nd!| }|jK                  d"      r|nd"| } ||||#      }tM        ||$      | _'        ntM        |&      | _'        d| _+        d| _,        | jZ                  r#| j]                  d'       | j]                  d(       yy# 1 sw Y   xY wc c}}w # 1 sw Y   xY w# tP        $ r, tS        jT                  |  d%       tM        |&      | _'        Y w xY w)*aj  Initialize the Deepgram STT service.

        Args:
            api_key: Deepgram API key for authentication.
            url: Custom Deepgram API base URL.

                .. deprecated:: 0.0.64
                    Parameter `url` is deprecated, use `base_url` instead.

            base_url: Custom Deepgram API base URL.
            encoding: Audio encoding format. Defaults to "linear16".
            channels: Number of audio channels. Defaults to 1.
            multichannel: Transcribe each audio channel independently.
                Defaults to False.
            sample_rate: Audio sample rate in Hz. If None, uses the pipeline
                sample rate.
            callback: Callback URL for async transcription delivery.
            callback_method: HTTP method for the callback (``"GET"`` or ``"POST"``).
            tag: Custom billing tag.
            mip_opt_out: Opt out of Deepgram model improvement program.
            live_options: Legacy configuration options.

                .. deprecated:: 0.0.105
                    Use ``settings=DeepgramSTTSettings(...)`` for runtime-updatable
                    fields and direct init parameters for connection-level config.

            addons: Additional Deepgram features to enable.
            should_interrupt: Whether to interrupt the bot when Deepgram VAD
                detects the user is speaking.

                .. deprecated:: 0.0.99
                    This parameter will be removed along with `vad_events` support.

            settings: Runtime-updatable settings. When provided alongside
                ``live_options``, ``settings`` values take precedence (applied
                after the ``live_options`` merge).
            ttfs_p99_latency: P99 latency from speech end to final transcript in seconds.
                Override for your deployment. See https://github.com/pipecat-ai/stt-benchmark
            **kwargs: Additional arguments passed to the parent STTService.

        Note:
            The `vad_events` option in LiveOptions is deprecated as of version 0.0.99 and will be removed in a future version. Please use the Silero VAD instead.
        r   Nalwaysz6Parameter 'url' is deprecated, use 'base_url' instead.r4   znova-3-generalr2   r)   Fr*   r+   r-   r/   Tr0   r1   r6   r7   r8   r9   r:   r<   r=   r?   r@   r   >   r>   r&   r(   r,   r3   r;   r5   r'   )r;   r   r   ztThe 'vad_events' parameter is deprecated and will be removed in a future version. Please use the Silero VAD instead.   )
stacklevel)DeepgramClientEnvironmentzwss://zhttps://)base
productionagent)r   environmentz?: Custom base_url configuration failed, falling back to default)r   on_speech_startedon_utterance_endrd   )/warningscatch_warningssimplefilterwarnDeprecationWarningrf   r   ENr   r;   r,   r(   r&   r'   r>   r3   r5   r[   rU   from_mappingapply_updater   superrG   _addons_should_interrupt	_encoding	_channels_multichannel	_callback_callback_method_tag_mip_opt_outr   r@   deepgramr   rV   r   _client	Exceptionr	   warning_connection_connection_taskvad_enabled_register_event_handler)rD   r   r   r   r,   r(   r5   r;   r&   r'   r>   r3   r   r   r   r   r   rE   r   default_settings	init_onlyrX   rY   lo_dictdeltar   ws_urlhttp_urlr   	__class__s                                rF   rG   zDeepgramSTTService.__init__  s!   @ ((* %%h/L& H / 
"
[[
 "
 	

 
 
 !
 
 
 
 "
 
 
 
 
  !
" "#
$ %
0 #">3FG++7K<O".":":K((4+44H((4+44H((4+44H//;&2&B&BO##/&**C++7".":":K,,8#/#<#<L		 -9,@,@,B,H,H,JaDAqaW`N`1a4aa+88A --e4 ))(3 	..0 	
#-%	
 		
 !1!!)! /	'>>$$((* %%h/9& 	   D>%-%8%8%B&QYPZH['/':'::'F8hW_V`La7!% 
  37P[\ /w?DL $(()<=(();< C B b> ,  Df[\  37C	Ds6   (MM!M.*M#AM% MM"%2NNc                 .    | j                   j                  S )zCheck if Deepgram VAD events are enabled.

        Returns:
            True if VAD events are enabled in the current settings.
        )r   r@   rD   s    rF   r   zDeepgramSTTService.vad_enabled  s     ~~(((rH   rQ   c                      y)zCheck if this service can generate processing metrics.

        Returns:
            True, as Deepgram service supports metrics generation.
        Trd   r   s    rF   can_generate_metricsz'DeepgramSTTService.can_generate_metrics  s     rH   r   c                 2  K   t         |   |       d{   }|s|S t        | j                  t              r| j                  j                          | j                  r0| j                          d{    | j                          d{    |S 7 z7  7 
w)z9Apply a settings delta and reconnect if anything changed.N)	r   _update_settings
isinstancer   rf   r   r   _disconnect_connect)rD   r   changedr   s      rF   r   z#DeepgramSTTService._update_settings  s     077N dnn&9:NN002""$$$--/!! 8 %!s4   BBAB2B3B
BBBBframec                 t   K   t         |   |       d{    | j                          d{    y7 7 w)zStart the Deepgram STT service.

        Args:
            frame: The start frame containing initialization parameters.
        N)r   startr   rD   r   r   s     rF   r   zDeepgramSTTService.start  s3      gmE"""mmo 	#   848688c                 t   K   t         |   |       d{    | j                          d{    y7 7 w)zXStop the Deepgram STT service.

        Args:
            frame: The end frame.
        N)r   stopr   r   s     rF   r   zDeepgramSTTService.stop  s6      gl5!!!    	" r   c                 t   K   t         |   |       d{    | j                          d{    y7 7 w)z]Cancel the Deepgram STT service.

        Args:
            frame: The cancel frame.
        N)r   cancelr   r   s     rF   r   zDeepgramSTTService.cancel  s6      gnU###    	$ r   audioc                x   K   | j                   r#| j                   j                  |       d{    d y7 
w)zSend audio data to Deepgram for transcription.

        Args:
            audio: Raw audio bytes to transcribe.

        Yields:
            Frame: None (transcription results come via WebSocket callbacks).
        N)r   
send_media)rD   r   s     rF   run_sttzDeepgramSTTService.run_stt  s5      ""--e444
 5s   +:8:c                 V   i }| j                   }t        |      D ]  }|j                  dv s|j                  j                  d      r-t	        ||j                        }t        |      r|Qt        |t              rt        |      j                         n
t        |      ||j                  <    t        |j                        r$|j                  t        |j                        |d<   t        |j                        r$|j                  t        |j                        |d<   | j                  |d<   t        | j                        |d<   t        | j                        j                         |d<   t        | j                        |d<   | j                   | j                   |d	<   | j"                  | j"                  |d
<   | j$                  t        | j$                        |d<   | j&                  &t        | j&                        j                         |d<   |j(                  j+                         D ]?  \  }}|	t        |t              rt        |      j                         n
t        |      ||<   A | j,                  r0| j,                  j+                         D ]  \  }}t        |      ||<    |S )zQBuild keyword arguments for ``client.listen.v1.connect()`` from current settings.)r4   r2   r.   rS   r4   r2   r,   r(   r5   r;   r&   r'   r>   r3   )r   r   rI   rV   r   r   r   rb   r`   lowerr4   r2   r   r   r   r;   r   r   r   r   r.   rU   r   )rD   rE   sr   valuer   s         rF   _build_connect_kwargsz(DeepgramSTTService._build_connect_kwargs"  s=   NN  	[Avv77166;L;LS;QAqvv&EE?em3=eT3JSZ--/PSTYPZF166N	[ AGG!4!!''lF7OAJJAJJ$:!$QZZF: "^^z 0z!$T%7%7!8!>!>!@~ #D$4$4 5}>>%!%F:  ,(,(=(=F$%99 		NF5M($'(9(9$:$@$@$BF=! ''--/ 	\JC 4>ud4Kc%j..0QTUZQ[s	\ <<"ll002 )
U!%js) rH   c                 ~   K   t        j                  d       | j                  | j                               | _        y w)NzConnecting to Deepgram)r	   debugcreate_task_connection_handlerr   r   s    rF   r   zDeepgramSTTService._connectP  s/     -. $ 0 01I1I1K Ls   ;=c                   K   | j                   sy t        j                  d       | j                  }d | _        |r|j	                          d {    | j                  | j                          d {    d | _         y 7 /7 w)NzDisconnecting from Deepgram)r   r	   r   r   send_close_streamcancel_task)rD   
connections     rF   r   zDeepgramSTTService._disconnectT  st     $$23 %%
..000t44555 $ 15s$   ABA="B0A?1B?Bc                 x  K   	 | j                         }	  | j                  j                  j                  j                  di |4 d{   }|| _        |j                  t        j                  | j                         |j                  t        j                  | j                         t        j                  |  d       | j                  | j                         |  d      }	 |j!                          d{    | j#                  |       d{    ddd      d{    d| _        +7 7 87 !# | j#                  |       d{  7   w xY w7 2# 1 d{  7  sw Y   BxY w# t$        j&                  $ r  t(        $ r$}t        j*                  |  d|        Y d}~d}~ww xY w# d| _        w xY ww)zManages the full WebSocket lifecycle inside a single async with block.

        Reconnects automatically after transient errors. Exits cleanly when
        the task is cancelled (i.e. on stop/cancel).
        Nz": Websocket connection initializedz::keepalivez: Connection lost, will retry: rd   )r   r   listenv1connectr   onr    MESSAGE_on_messageERROR	_on_errorr	   r   r   _keepalive_handlerstart_listeningr   asyncioCancelledErrorr   r   )rD   connect_kwargsr   keepalive_taskes        rF   r   z&DeepgramSTTService._connection_handlerd  s     !779N(94<<..1199KNK ? ?z'1D$MM)"3"3T5E5EFMM)//4>>BLLD6)K!LM%)%5%5//1dV;3G&N?(88:::"..~>>>? ?& $( - ? ;>d..~>>>? ? ? ? ))  L$'FqcJKKL $( s   F:4E+ 	D/
E+ BE%D58D19D5=ED3EE+ !E"E+ &	F:/E+ 1D53E5E
E
EEE+ E(EE($E+ +F+F&!F. &F++F. .	F77F:c                 >  K   	 t        j                  d       d{    | j                  r;	 | j                  j                          d{    t	        j
                  |  d       e7 L7 # t        $ r$}t	        j                  |  d|        Y d}~-d}~ww xY ww)zPeriodically send KeepAlive frames to prevent server-side timeout.

        Deepgram closes inactive connections after 10 seconds (NET-0001 error).
        Sending every 5 seconds stays within the recommended 3-5 second interval.
           Nz: Sent keepalivez: Keepalive failed: )r   sleepr   send_keep_aliver	   tracer   r   )rD   r   s     rF   r   z%DeepgramSTTService._keepalive_handler  s      --"""E**::<<<LLD6)9!:; " =  ENNdV+?s#CDDEsJ   BA)BA- A+A- (B+A- -	B6BBBBc                 @   K   | j                          d{    y7 w)z7Start processing metrics collection for this utterance.N)start_processing_metricsr   s    rF   _start_metricsz!DeepgramSTTService._start_metrics  s     ++---s   c                    K   t        j                  |  d|        | j                  |        d {    | j                          d {    y 7 7 w)Nz connection error, will retry: )	error_msg)r	   r   
push_errorstop_all_metrics)rD   errors     rF   r   zDeepgramSTTService._on_error  sO     $>ugFGoo5'o333##%%% 	4%s!   1AAAAAAc                   K   | j                          d {    | j                  d|       d {    | j                  t               d {    | j                  r| j                          d {    y y 7 a7 I7 .7 w)Nr   )r  _call_event_handlerbroadcast_framer   r   broadcast_interruptionrD   messages     rF   _on_speech_startedz%DeepgramSTTService._on_speech_started  su     !!###&&':GDDD""#;<<<!!--/// " 	$D</sC   B A8B A:B A<#B 1A>2B :B <B >B c                    K   | j                  d|       d {    | j                  t               d {    y 7 "7 w)Nr   )r  r	  r   r  s     rF   _on_utterance_endz$DeepgramSTTService._on_utterance_end  s<     &&'97CCC""#;<<< 	D<s   ?;?=??
transcriptis_finalr2   c                    K   yw)z+Handle a transcription result with tracing.Nrd   )rD   r  r  r2   s       rF   _handle_transcriptionz(DeepgramSTTService._handle_transcription  s     
 	s   c           	      D  K   t        |t              r'| j                  r| j                  |       d {    y y t        |t              r'| j                  r| j                  |       d {    y y t        |t              r|j                  r"t        |j                  j                        dk(  ry |j                  }|j                  j                  d   j                  }d }|j                  j                  d   j                  r1|j                  j                  d   j                  d   }t        |      }t        |      dkD  r|rt        |dd      xs d}|r| j                          | j!                  t#        || j$                  t'               ||             d {    | j)                  |||       d {    | j+                          d {    y | j!                  t-        || j$                  t'               ||             d {    y y y 7 7 7 z7 a7 K7 w)Nr   from_finalizeF)rZ   )r   r"   r   r  r#   r  r!   channellenalternativesr  r  	languagesr   r   confirm_finalize
push_framer   _user_idr   r  stop_processing_metricsr   )rD   r  r  r  r2   r  s         rF   r   zDeepgramSTTService._on_message  s    g45--g666  !56,,W555  1??c'//*F*F&G1&L''H 55a8CCJH++A.88"??77:DDQG#H-:" %,G_e$L$UPUM$--///*& MM,.$#*   44Z8TTT66888 //1& MM,.$#*  ) # 2	 7 6" U8sj   1H H6H *H+D2H HH 8H9H H9H 
HH H H H H H 	directionc                   K   t         |   ||       d{    t        |t              r%| j                  s| j                          d{    yt        |t              re| j                  rX| j                          | j                  j                          d{    t        j                  d|j                  d|       yyy7 7 }7 0w)zProcess frames with Deepgram-specific handling.

        Args:
            frame: The frame to process.
            direction: The direction of frame processing.
        Nz(Triggered finalize event on: frame.name=z, direction=)r   process_framer   r   r   r  r   r   request_finalizesend_finalizer	   r   rI   )rD   r   r  r   s      rF   r   z DeepgramSTTService.process_frame  s      g#E9555e89$BRBR%%''':; %%'&&44666HUZZMI<XY   < 	6 ( 7s4   CC3CC	ACC-C	CCrh   )0r\   r]   r^   r_   rf   Settingsr   r   r`   ra   rb   r   r   r%   rc   floatrG   propertyr   r   r   r   r   r   r   r   r
   r   bytesr   r   r   r   r   r   r   r   r  r   r  r  r   r   r  r   r   r   __classcell__)r   s   @rF   r   r      s*   " #H"" ""%)"&)-!&*.2!%!%26,=%F= F= 	F=
 F= F= F= F= c]F= 3-F= "#F= c]F= d^F= {+F= F=  !F=" ./#F=$ #5/%F=P ) )d K DcN " ! !!+ !5 ^E4K-H ,t ,\M% (<E.&0= NR)-9A(9K ,\Z Z> Z ZrH   r   )8r_   r   dataclassesr   r   r   typingr   r   r   logurur	   pipecat.frames.framesr
   r   r   r   r   r   r   r   r   r   "pipecat.processors.frame_processorr   pipecat.services.settingsr   r   r   r   r   pipecat.services.stt_latencyr   pipecat.services.stt_servicer   pipecat.transcriptions.languager   pipecat.utils.timer   (pipecat.utils.tracing.service_decoratorsr   r   r   deepgram.core.eventsr    deepgram.listen.v1.typesr!   r"   r#   ModuleNotFoundErrorr   r  r   r%   rf   r   rd   rH   rF   <module>r6     s    6  0 0 0 0    >  ; 3 4 / ?,,. x xv E$+ E$ E$PsZ sZU  ,FLL;qc"#FLL\]
&qc*
++,s   ,B( (C$-2CC$