
    qi                     2   d Z ddlZddlZddlZddlZddlZddlmZmZ ddl	m
Z
 dej                  d<   ddlmZmZmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZmZmZmZmZmZ ddlm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z)m*Z* ddl+m,Z, 	 ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: de)dee?   fdZ@e G d de!             ZA G d d e'      ZBy# e;$ r7Z< ejz                  de<         ejz                  d        e>de<       dZ<[<ww xY w)!a   Google Cloud Speech-to-Text V2 service implementation for Pipecat.

This module provides a Google Cloud Speech-to-Text V2 service with streaming
support, enabling real-time speech recognition with features like automatic
punctuation, voice activity detection, and multi-language support.
    N)	dataclassfield)
traced_sttfalseGRPC_ENABLE_FORK_SUPPORT)AnyAsyncGeneratorListOptionalUnion)logger)	BaseModelFieldfield_validator)CancelFrameEndFrameFrameInterimTranscriptionFrame
StartFrameTranscriptionFrame)	NOT_GIVENSTTSettings	_NotGiven_warn_deprecated_param)GOOGLE_TTFS_P99)
STTService)Languageresolve_language)time_now_iso8601)ClientOptions)Aborted)default)GoogleAuthError)	speech_v2)cloud_speech)service_accountzException: zIn order to use Google AI, you need to `pip install pipecat-ai[google]`. Also, set `GOOGLE_APPLICATION_CREDENTIALS` environment variable.zMissing module: languagereturnc                    i t         j                  dt         j                  dt         j                  dt         j                  dt         j
                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  d	t         j                  d
t         j                  dt         j                   dt         j"                  di t         j$                  dt         j&                  dt         j(                  dt         j*                  dt         j,                  dt         j.                  dt         j0                  dt         j2                  dt         j4                  dt         j6                  dt         j8                  dt         j:                  dt         j<                  dt         j>                  dt         j@                  dt         jB                  dt         jD                  di t         jF                  dt         jH                  dt         jJ                  dt         jL                  dt         jN                  dt         jP                  dt         jR                  dt         jT                  dt         jV                  dt         jX                  dt         jZ                  dt         j\                  d t         j^                  d t         j`                  d!t         jb                  d!t         jd                  d"t         jf                  d"i t         jh                  d#t         jj                  d$t         jl                  d#t         jn                  d%t         jp                  d&t         jr                  d't         jt                  d(t         jv                  d)t         jx                  d*t         jz                  d+t         j|                  d,t         j~                  d-t         j                  d.t         j                  d/t         j                  d0t         j                  d1t         j                  d2i t         j                  d%t         j                  d3t         j                  d4t         j                  d4t         j                  d5t         j                  d5t         j                  d6t         j                  d6t         j                  d7t         j                  d8t         j                  d9t         j                  d:t         j                  d7t         j                  d;t         j                  d;t         j                  d<t         j                  d<i t         j                  d=t         j                  d>t         j                  d?t         j                  d=t         j                  d@t         j                  d@t         j                  dAt         j                  dAt         j                  dBt         j                  dBt         j                  dCt         j                  dCt         j                  dDt         j                  dDt         j                  dEt         j                  dEt         j                  dFi t         j                  dFt         j                  dGt         j                  dGt         j                  dHt         j                  dIt         j                  dIt         j                  dJt         j                  dJt         j                  dKt         j                  dKt         j                  dLt         j                  dLt         j                  dMt         j                  dMt         j                  dNt         j                  dNt         j                  dOi t         j                  dOt         j                  dPt         j                  dPt         j                  dQt         j                  dQt         j                  dRt         j                  dRt         j                  dSt         j                   dSt         j                  dTt         j                  dTt         j                  dUt         j                  dUt         j
                  dVt         j                  dVt         j                  dWt         j                  dWi t         j                  dXt         j                  dXt         j                  dXt         j                  dYt         j                  dYt         j                  dZt         j                  dZt         j                   d[t         j"                  d\t         j$                  d[t         j&                  d]t         j(                  d]t         j*                  d^t         j,                  d^t         j.                  d_t         j0                  d_t         j2                  d`i t         j4                  d`t         j6                  dat         j8                  dat         j:                  dbt         j<                  dbt         j>                  dct         j@                  dct         jB                  ddt         jD                  det         jF                  dft         jH                  dgt         jJ                  dht         jL                  dit         jN                  djt         jP                  dkt         jR                  ddt         jT                  dli t         jV                  dmt         jX                  dnt         jZ                  dot         j\                  dpt         j^                  dqt         j`                  drt         jb                  dst         jd                  dtt         jf                  dut         jh                  dvt         jj                  dwt         jl                  dxt         jn                  dxt         jp                  dyt         jr                  dzt         jt                  dyt         jv                  d{i t         jx                  d{t         jz                  d|t         j|                  d|t         j~                  d}t         j                  d~t         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  dt         j                  di}t        | |d      S )zMaps Language enum to Google Speech-to-Text V2 language codes.

    Args:
        language: Language enum value.

    Returns:
        Optional[str]: Google STT language code or None if not supported.
    zaf-ZAzsq-ALzam-ETzar-EGzar-AEzar-BHzar-DZzar-IQzar-JOzar-KWzar-LBzar-MAzar-OMzar-QAzar-SAzar-SYzar-TNzar-YEzhy-AMzaz-AZzeu-ESzbn-INzbn-BDzbs-BAzbg-BGzmy-MMzca-ESzcmn-Hans-CNzcmn-Hans-HKzcmn-Hant-TWzyue-Hant-HKzhr-HRzcs-CZzda-DKznl-NLznl-BEen-USzen-AUzen-CAzen-GBzen-GHzen-HKzen-INzen-IEzen-KEzen-NGzen-NZzen-PHzen-SGzen-TZzen-ZAzet-EEzfil-PHzfi-FIzfr-FRzfr-BEzfr-CAzfr-CHzgl-ESzka-GEzde-DEzde-ATzde-CHzel-GRzgu-INziw-ILzhi-INzhu-HUzis-ISzid-IDzit-ITzit-CHzja-JPzjv-IDzkn-INzkk-KZzkm-KHzko-KRzlo-LAzlv-LVzlt-LTzmk-MKzms-MYzml-INzmr-INzmn-MNzne-NPzno-NOzfa-IRzpl-PLzpt-PTzpt-BRz
pa-Guru-INzro-ROzru-RUzsr-RSzsi-LKzsk-SKzsl-SIzes-ESzes-ARzes-BOzes-CLzes-COzes-CRzes-DOzes-ECzes-GTzes-HNzes-MXzes-NIzes-PAzes-PEzes-PRzes-PYzes-SVzes-USzes-UYzes-VEzsu-IDzsw-TZzsw-KEzsv-SEzta-INzta-MYzta-SGzta-LKzte-INzth-THztr-TRzuk-UAzur-INzur-PKzuz-UZzvi-VNzxh-ZAzzu-ZAF)use_base_code)r   AFAF_ZASQSQ_ALAMAM_ETARAR_AEAR_BHAR_DZAR_EGAR_IQAR_JOAR_KWAR_LBAR_MAAR_OMAR_QAAR_SAAR_SYAR_TNAR_YEHYHY_AMAZAZ_AZEUEU_ESBNBN_BDBN_INBSBS_BABGBG_BGMYMY_MMCACA_ESZHZH_CNZH_HKZH_TWYUEYUE_CNHRHR_HRCSCS_CZDADA_DKNLNL_BENL_NLENEN_AUEN_CAEN_GBEN_GHEN_HKEN_INEN_IEEN_KEEN_NGEN_NZEN_PHEN_SGEN_TZEN_USEN_ZAETET_EEFILFIL_PHFIFI_FIFRFR_BEFR_CAFR_CHFR_FRGLGL_ESKAKA_GEDEDE_ATDE_CHDE_DEELEL_GRGUGU_INHEHE_ILHIHI_INHUHU_HUISIS_ISIDID_IDITIT_ITIT_CHJAJA_JPJVJV_IDKNKN_INKKKK_KZKMKM_KHKOKO_KRLOLO_LALVLV_LVLTLT_LTMKMK_MKMSMS_MYMLML_INMRMR_INMNMN_MNNENE_NPNONBNB_NOFAFA_IRPLPL_PLPTPT_BRPT_PTPAPA_INRORO_RORURU_RUSRSR_RSSISI_LKSKSK_SKSLSL_SIESES_ARES_BOES_CLES_COES_CRES_DOES_ECES_ESES_GTES_HNES_MXES_NIES_PAES_PEES_PRES_PYES_SVES_USES_UYES_VESUSU_IDSWSW_KESW_TZSVSV_SETATA_INTA_MYTA_SGTA_LKTETE_INTHTH_THTRTR_TRUKUK_UAURUR_INUR_PKUZUZ_UZVIVI_VNXHZUZU_ZAr   )r'   LANGUAGE_MAPs     M/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/google/stt.pylanguage_to_google_stt_languager  >   sU   ]W] 	]
 	W] 	] 	W] 	] 	W] 	] 	] 	] 	]  	!]" 	#]$ 	%]& 	']( 	)]* 	+], 	-]. 	/]0 	1]2 	3]4 	5]8 	W9]: 	;]> 	W?]@ 	A]D 	WE]F 	G]J 	WK]L 	M]N 	O]R 	WS]T 	U]X 	WY]Z 	[]^ 	W_]` 	a]d 	We]f 	g]j 	]k]l 	m]n 	o]p 	q]r 	ms]t 	u]x 	Wy]z 	{]~ 	W]@ 	A]D 	WE]F 	G]J 	WK]L 	M]N 	O]R 	WS]T 	U]V 	W]X 	Y]Z 	[]\ 	]]^ 	_]` 	a]b 	c]d 	e]f 	g]h 	i]j 	k]l 	m]n 	o]p 	q]t 	Wu]v 	w]z 	h{]| 	}]@ 	WA]B 	C]F 	WG]H 	I]J 	K]L 	M]N 	O]R 	WS]T 	U]X 	WY]Z 	[]^ 	W_]` 	a]b 	c]d 	e]h 	Wi]j 	k]n 	Wo]p 	q]t 	Wu]v 	w]z 	W{]| 	}]@ 	WA]B 	C]F 	WG]H 	I]L 	WM]N 	O]R 	WS]T 	U]V 	W]Z 	W[]\ 	]]` 	Wa]b 	c]f 	Wg]h 	i]l 	Wm]n 	o]r 	Ws]t 	u]x 	Wy]z 	{]~ 	W]@ 	A]D 	WE]F 	G]J 	WK]L 	M]P 	WQ]R 	S]V 	WW]X 	Y]\ 	W]]^ 	_]b 	Wc]d 	e]h 	Wi]j 	k]n 	Wo]p 	q]t 	Wu]v 	Ww]x 	y]| 	W}]~ 	]B 	WC]D 	E]H 	WI]J 	K]L 	M]P 	\Q]R 	S]V 	WW]X 	Y]\ 	W]]^ 	_]b 	Wc]d 	e]h 	Wi]j 	k]n 	Wo]p 	q]t 	Wu]v 	w]z 	W{]| 	}]~ 	]@ 	A]B 	C]D 	E]F 	G]H 	I]J 	K]L 	M]N 	O]P 	Q]R 	S]T 	U]V 	W]X 	Y]Z 	[]\ 	]]^ 	_]` 	a]b 	c]f 	Wg]h 	i]l 	Wm]n 	o]p 	q]t 	Wu]v 	w]z 	W{]| 	}]~ 	]@ 	A]B 	C]F 	WG]H 	I]L 	WM]N 	O]R 	WS]T 	U]X 	WY]Z 	[]^ 	W_]` 	a]b 	c]f 	WWWWy]L~ Hl%HH    c                      e Zd ZU dZ ed       Zee   ez  e	d<    ed       Z
e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<   y)GoogleSTTSettingsa  Settings for GoogleSTTService.

    Parameters:
        languages: List of ``Language`` enums for recognition
            (e.g. ``[Language.EN_US]``). Preferred over ``language_codes``.
        language_codes: List of Google STT language code strings
            (e.g. ``["en-US"]``).

            .. deprecated:: 0.0.104
                Use ``languages`` instead. If both are provided, ``languages``
                takes precedence. This field is here just for backward
                compatibility with dict-based settings updates.
        use_separate_recognition_per_channel: Process each audio channel separately.
        enable_automatic_punctuation: Add punctuation to transcripts.
        enable_spoken_punctuation: Include spoken punctuation in transcript.
        enable_spoken_emojis: Include spoken emojis in transcript.
        profanity_filter: Filter profanity from transcript.
        enable_word_time_offsets: Include timing information for each word.
        enable_word_confidence: Include confidence scores for each word.
        enable_interim_results: Stream partial recognition results.
        enable_voice_activity_events: Detect voice activity in audio.
    c                      t         S Nr    r  r   <lambda>zGoogleSTTSettings.<lambda>      ) r  default_factory	languagesc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  r
  r  language_codesc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  s    	 r  $use_separate_recognition_per_channelc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>      S\ r  enable_automatic_punctuationc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  s    PY r  enable_spoken_punctuationc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  s    9 r  enable_spoken_emojisc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  s    y r  profanity_filterc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  s    y r  enable_word_time_offsetsc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>      Y r  enable_word_confidencec                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  r  r  enable_interim_resultsc                      t         S r  r  r  r  r   r	  zGoogleSTTSettings.<lambda>  r  r  enable_voice_activity_eventsN)__name__
__module____qualname____doc__r   r  r
   r   r   __annotations__r  strr  boolr  r  r  r  r  r  r!  r#  r  r  r   r  r  i  s   . -2BS,TItH~	)T,1BS,TNDI	)T=B)>($*:  6;K\5] $"2]27HY2Zti/Z-2CT-U$*U).?P)QdY&Q16GX1YdY.Y/4EV/WD9,W/4EV/WD9,W5:K\5] $"2]r  r  c                   F    e Zd ZU dZeZeed<   dZ G d de      Z	dddddde
dd	ee   d
ee   dedee   dee	   dee   dee   f fdZdefdZdeee   z  deee   z  fdZdee   fdZd Zde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dddddddddddde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dfd)Z!d* Z"d+ Z#d, Z$d- Z%d.e&de'e(df   fd/Z)e*	 d4d0ed1edee   fd2       Z+d3 Z, xZ-S )5GoogleSTTServicea  Google Cloud Speech-to-Text V2 service implementation.

    Provides real-time speech recognition using Google Cloud's Speech-to-Text V2 API
    with streaming support. Handles audio transcription and optional voice activity detection.
    Implements automatic stream reconnection to handle Google's 4-minute streaming limit.

    Parameters:
        InputParams: Configuration parameters for the STT service.
        STREAMING_LIMIT: Google Cloud's streaming limit in milliseconds (4 minutes).

    Raises:
        ValueError: If neither credentials nor credentials_path is provided.
        ValueError: If project ID is not found in credentials.
    	_settingsi c                   Z   e Zd ZU dZ ed       Zeeee   f   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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<    edd      edee   fd              Zedee   fd       Zy)GoogleSTTService.InputParamsa  Configuration parameters for Google Speech-to-Text.

        .. deprecated:: 0.0.105
            Use ``settings=GoogleSTTSettings(...)`` instead.

        Parameters:
            languages: Single language or list of recognition languages. First language is primary.
            model: Speech recognition model to use.
            use_separate_recognition_per_channel: Process each audio channel separately.
            enable_automatic_punctuation: Add punctuation to transcripts.
            enable_spoken_punctuation: Include spoken punctuation in transcript.
            enable_spoken_emojis: Include spoken emojis in transcript.
            profanity_filter: Filter profanity from transcript.
            enable_word_time_offsets: Include timing information for each word.
            enable_word_confidence: Include confidence scores for each word.
            enable_interim_results: Stream partial recognition results.
            enable_voice_activity_events: Detect voice activity in audio.
        c                  $    t         j                  gS r  )r   rp   r  r  r   r	  z%GoogleSTTService.InputParams.<lambda>  s    T\TbTbSc r  r  r  latest_longmodelFr  Tr  r  r  r  r  r  r!  r#  before)moder(   c                 ,    t        |t              r|gS |S )zEnsure languages is always a list.

            Args:
                v: Single Language enum or list of Language enums.

            Returns:
                List[Language]: List of configured languages.
            )
isinstancer   )clsvs     r   validate_languagesz/GoogleSTTService.InputParams.validate_languages  s     !X&s
Hr  c                 R    t        | j                  t              sJ | j                  S )zGet languages as a guaranteed list.

            Returns:
                List[Language]: List of configured languages.
            )r6  r  listselfs    r   language_listz*GoogleSTTService.InputParams.language_list  s"     dnnd333>>!r  N)r$  r%  r&  r'  r   r  r   r   r
   r(  r2  r   r)  r  r*  r  r  r  r  r  r  r!  r#  r   classmethodr9  propertyr>  r  r  r   InputParamsr/    s   	& 6;Kc5d	54>12d,x},?D,htnD7;$htn;49!8D>9/4htn4+0(4.038 (4.81661557<$htn<	8	4		$x. 	 
 
5	 
	"4> 	" 
	"r  rA  Nglobal)credentialscredentials_pathlocationsample_rateparamssettingsttfs_p99_latencyrC  rD  rE  rF  rG  rH  rI  c                   t        dt        j                  gddddddddddd      }	|t        dt                |st	        |j
                        |	_        |j                  |	_        |j                  |	_        |j                  |	_	        |j                  |	_
        |j                  |	_        |j                  |	_        |j                  |	_        |j                  |	_        |j                  |	_        |j                   |	_        ||	j#                  |       t%        | L  d|||	d| || _        d| _        d| _        d| _        d| _        g | _        g | _        d| _        d| _        d| _        d| _        d| _        d| _         d| _!        d}
| j(                  d	k7  rtE        | j(                   d
      }
d}|rKtG        jH                  |      }|jK                  d      | _&        tN        jP                  jS                  |      }ny|r_tU        |      5 }tG        jV                  |      }|jK                  d      | _&        ddd       tN        jP                  jY                  |      }n	 t[        dg      \  }}|| _&        |st_        d      | jL                  st_        d      ta        jb                  ||
      | _2        y# 1 sw Y   xY w# t\        $ r Y Xw xY w)a  Initialize the Google STT service.

        Args:
            credentials: JSON string containing Google Cloud service account credentials.
            credentials_path: Path to service account credentials JSON file.
            location: Google Cloud location (e.g., "global", "us-central1").
            sample_rate: Audio sample rate in Hertz.
            params: Configuration parameters for the service.

                .. deprecated:: 0.0.105
                    Use ``settings=GoogleSTTSettings(...)`` instead.

            settings: Runtime-updatable settings. When provided alongside deprecated
                ``params``, ``settings`` values take precedence.
            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 STTService.
        Nr1  FT)r'   r  r  r2  r  r  r  r  r  r  r  r!  r#  rG  )rF  rI  rH  r   rB  z-speech.googleapis.com)api_endpoint
project_idz.https://www.googleapis.com/auth/cloud-platform)scopeszNo valid credentials provided.z#Project ID not found in credentials)rC  client_optionsr  )3r  r   rp   r   r;  r>  r  r2  r  r  r  r  r  r  r  r!  r#  apply_updatesuper__init__	_location_stream_config_streaming_task_stream_start_time_last_audio_input_audio_input_result_end_time_is_final_end_time_final_request_end_time_bridging_offset_last_transcript_was_final_new_stream_restart_counterr    jsonloadsget_project_idr&   Credentialsfrom_service_account_infoopenloadfrom_service_account_filer"   r#   
ValueErrorr$   SpeechAsyncClient_client)r=  rC  rD  rE  rF  rG  rH  rI  kwargsdefault_settingsrN  credsjson_account_infofrL  	__class__s                  r   rQ  zGoogleSTTService.__init__  s   > -~~&16)-&+!&"%*#(#').
& "8->?-1&2F2F-G *)/ &?? !E AG@c@c ==C=]=] :8>8S8S 54:4K4K 1<B<[<[ 9:@:W:W 7:@:W:W 7@F@c@c = ))(3 	
#-%	
 		
 "# #$!# !"#'($ !*/' ! >>X%*4>>:JJ`8abN 8< $

; 7044\BD#//IIJ[\E&' G1$(IIaL!#4#8#8#F G $//IIJZ[E$+LM%!z $.  =>>BCC 22uUcd'G G # s   ,J<$K <K	KKr(   c                      y)zCheck if the service can generate metrics.

        Returns:
            bool: True, as this service supports metrics generation.
        Tr  r<  s    r   can_generate_metricsz%GoogleSTTService.can_generate_metricsc  s     r  r'   c                     t        |t              r|D cg c]  }t        |      xs d c}S t        |      xs dS c c}w )zConvert Language enum(s) to Google STT language code(s).

        Args:
            language: Single Language enum or list of Language enums.

        Returns:
            str | List[str]: Google STT language code(s).
        r*   )r6  r;  r  )r=  r'   langs      r   language_to_service_languagez-GoogleSTTService.language_to_service_languagek  sC     h%QYZ3D9DWDZZ.x8CGC [s   =c                    | j                   j                  r3| j                   j                  D cg c]  }| j                  |       c}S | j                   j                  rt	        | j                   j                        S dgS c c}w )a-  Resolve the current language settings to Google STT language code strings.

        Prefers ``languages`` (``Language`` enums) over the deprecated
        ``language_codes`` (raw strings). Falls back to ``["en-US"]``.

        Returns:
            List[str]: Google STT language code strings.
        r*   )r-  r  rv  r  r;  )r=  ru  s     r   _get_language_codesz$GoogleSTTService._get_language_codesx  sg     >>##HLH`H`aD55d;aa>>((5566y bs   Bc                    K   | j                   rFt        j                  d       | j                          d{    | j	                          d{    yy7 7 w)z.Reconnect the stream if it's currently active.z0Reconnecting stream due to configuration changesN)rU  r   debug_disconnect_connectr<  s    r   _reconnect_if_neededz%GoogleSTTService._reconnect_if_needed  sI     LLKL""$$$--/!!  $!s!   5AAAAAAr  c                 H  K   t        j                         5  t        j                  d       t        j                  dt               ddd       t        j                  d|        | j                  t        t        |                   d{    y# 1 sw Y   NxY w7 w)a#  Update the service's recognition languages.

        .. deprecated:: 0.0.104
            Use ``STTUpdateSettingsFrame`` with ``GoogleSTTSettings(languages=...)``
            instead.

        Args:
            languages: List of languages for recognition. First language is primary.
        alwayszhset_languages() is deprecated. Use STTUpdateSettingsFrame with GoogleSTTSettings(languages=...) instead.NzSwitching STT languages to: )r  )
warningscatch_warningssimplefilterwarnDeprecationWarningr   rz  _update_settingsr  r;  )r=  r  s     r   set_languageszGoogleSTTService.set_languages  s      $$& 	!!(+MM<"	 	3I;?@##$5Y$PQQQ	 	 	Rs)   B"0BAB"B B"BB"deltac                   K   ddl m}  ||j                        r|j                  g|_        t        |_         ||j
                        rNt        j                         5  t        j                  d       t        j                  dt        d       ddd       t        | 1  |       d{   }|r| j                          d{    |S # 1 sw Y   <xY w7 ,7 w)a  Apply settings delta and reconnect if anything changed.

        Handles ``language`` from base ``set_language`` by converting it to
        ``languages``. Emits a deprecation warning if ``language_codes`` is
        used. All other fields (model, boolean flags) are applied directly.
        Reconnects the stream on any change.

        Args:
            delta: A settings delta.

        Returns:
            Dict mapping changed field names to their previous values.
        r   )is_givenr  ziGoogleSTTSettings.language_codes is deprecated. Use GoogleSTTSettings.languages (List[Language]) instead.   )
stacklevelN)pipecat.services.settingsr  r'   r  r   r  r  r  r  r  r  rP  r  r}  )r=  r  r  changedrq  s       r   r  z!GoogleSTTService._update_settings  s      	7 ENN#$~~.EO&EN E(()((* %%h/P& 	 077++---  8 .s<   AC2CC+C,CCCCCCframec                 t   K   t         |   |       d{    | j                          d{    y7 7 w)zStart the STT service and establish connection.

        Args:
            frame: The start frame triggering the service start.
        N)rP  startr|  r=  r  rq  s     r   r  zGoogleSTTService.start  s3      gmE"""mmo 	#   848688c                 t   K   t         |   |       d{    | j                          d{    y7 7 w)zStop the STT service and clean up resources.

        Args:
            frame: The end frame triggering the service stop.
        N)rP  stopr{  r  s     r   r  zGoogleSTTService.stop  s6      gl5!!!    	" r  c                 t   K   t         |   |       d{    | j                          d{    y7 7 w)zCancel the STT service and clean up resources.

        Args:
            frame: The cancel frame triggering the service cancellation.
        N)rP  cancelr{  r  s     r   r  zGoogleSTTService.cancel  s6      gnU###    	$ r  )r  r2  r  r  r  r  r  r  r!  r#  rE  r2  r  r  r  r  r  r  r!  r#  c                  K   t        j                         5  t        j                  d       t        j                  dt               ddd       t               }|t        |      |_        |||_        |||_	        |||_
        |||_        |||_        |||_        |||_        |	|	|_        |
|
|_        |t#        j$                  d|        || _        | j)                  |       d{    y# 1 sw Y   xY w7 w)a  Update service options dynamically.

        .. deprecated::
            Use ``STTUpdateSettingsFrame`` with ``GoogleSTTSettings(...)``
            instead.

        Args:
            languages: New list of recognition languages.
            model: New recognition model.
            enable_automatic_punctuation: Enable/disable automatic punctuation.
            enable_spoken_punctuation: Enable/disable spoken punctuation.
            enable_spoken_emojis: Enable/disable spoken emojis.
            profanity_filter: Enable/disable profanity filter.
            enable_word_time_offsets: Enable/disable word timing info.
            enable_word_confidence: Enable/disable word confidence scores.
            enable_interim_results: Enable/disable interim results.
            enable_voice_activity_events: Enable/disable voice activity detection.
            location: New Google Cloud location.

        Note:
            Changes that affect the streaming configuration will cause
            the stream to be reconnected.
        r  z_update_options() is deprecated. Use STTUpdateSettingsFrame with GoogleSTTSettings(...) instead.NzUpdating location to: )r  r  r  r  r  r  r;  r  r2  r  r  r  r  r  r  r!  r#  r   rz  rR  r  )r=  r  r2  r  r  r  r  r  r  r!  r#  rE  r  s                r   update_optionszGoogleSTTService.update_options  s     L $$& 	!!(+MM2"	 "# "9oEOEK'31ME.$0.GE++)=E&'%5E"#/-EE*!-+AE(!-+AE('31ME.LL1(<=%DN##E***G	 	F 	+s)   D0C7B*D1D2D7D <Dc                   K   t        j                  d       t        t        j                         dz        | _        d| _        t        j                  t        j                  t        j                  t        j                  j                  j                  | j                  d      | j                         | j                  j                  t        j                   | j                  j"                  | j                  j$                  | j                  j&                  | j                  j(                  | j                  j*                  | j                  j,                              t        j.                  | j                  j0                  | j                  j2                        	      | _        t7        j8                         | _        | j=                  | j?                               | _         | jC                  d
       d{    y7 w)z3Initialize streaming recognition config and stream.z#Connecting to Google Speech-to-Text  T   )encodingsample_rate_hertzaudio_channel_count)r  r  r  r  r  r  )explicit_decoding_configr  r2  features)r#  interim_results)configstreaming_featureson_connectedN)"r   rz  inttimerV  r^  r%   StreamingRecognitionConfigRecognitionConfigExplicitDecodingConfigAudioEncodingLINEAR16rF  rx  r-  r2  RecognitionFeaturesr  r  r  r  r  r  StreamingRecognitionFeaturesr#  r!  rT  asyncioQueue_request_queuecreate_task_stream_audiorU  _call_event_handlerr<  s    r   r|  zGoogleSTTService._connect0  se    :; #&diikD&8"9#>>11)5)L)L)@@NNWW&*&6&6()*
  $779nn**%99151\1\.2nn.V.V)-)L)L%)^^%D%D-1^^-T-T+/>>+P+P"  ,HH-1^^-X-X $ E E %
0 &mmo#//0B0B0DE&&~666s   G8H:H ;Hc                    K   | j                   r?t        j                  d       | j                  | j                          d{    d| _         | j	                  d       d{    y7 %7 w)z)Clean up streaming recognition resources.z(Disconnecting from Google Speech-to-TextNon_disconnected)rU  r   rz  cancel_taskr  r<  s    r   r{  zGoogleSTTService._disconnectU  s^     LLCD""4#7#7888#'D &&'8999 9 	:s$   A A,A(A,"A*#A,*A,c                N  K   d| j                    d| j                   d}t        j                  d|        	 t	        j
                  || j                         	 | j                  j                          d{   }| j                  j                          t        t        j                         dz        | j                  z
  | j                  kD  rft        j                  d       | j                  | _        g | _        | xj"                  d	z  c_        | j                  j%                  |       d{    y| j                  j'                  |       t	        j
                  |
       7 7 =# t(        $ r%}| j+                  d| |       d{  7    d}~ww xY ww)z6Generates requests for the streaming recognize method.z	projects/z/locations/z/recognizers/_zUsing recognizer path: )
recognizerstreaming_configNr  z9Streaming limit reached, initiating graceful reconnectionr  )audioUnknown error occurred: 	error_msg	exception)rc  rR  r   tracer%   StreamingRecognizeRequestrT  r  rb  	task_doner  r  rV  STREAMING_LIMITrz  rX  rW  r_  putappend	Exception
push_error)r=  recognizer_path
audio_dataes       r   _request_generatorz#GoogleSTTService._request_generator^  sn    %d&6&6%7{4>>BRR`a..?@A	88*!% 
 #'#6#6#:#:#<<
##--/ 		d*+d.E.EEI]I]]LL!\]-1->->D*(*D%))Q.)--11*===!!((4"<<:NN# < >  	//.Fqc,JVW/XXX	sZ   6F%AE4 ;E0<B8E4 4E25E4 9F%:7E4 2E4 4	F"=FFFF""F%c                 l  K   	 	 	 | j                   j                         rt        j                  d       d{    :| j                  j                  | j                                d{   }| j                  |       d{    t        t        j                         dz        | j                  z
  | j                  kD  r;t        j                  d       t        t        j                         dz        | _
        ny	 7 7 7 # t        $ rl}| j                  d| |       d{  7   t        j                  d       d{  7   t        t        j                         dz        | _
        Y d}~wd}~ww xY w# t        $ r)}| j                  d| |       d{  7   Y d}~yd}~ww xY ww)	z0Handle bi-directional streaming with Google STT.g{Gz?N)requestsr  z!Reconnecting stream after timeoutr  r  r  )r  emptyr  sleeprk  streaming_recognizer  _process_responsesr  r  rV  r  r   rz  r  r  )r=  r  r  s      r   r  zGoogleSTTService._stream_audio  s     	YF**002%mmD111  150P0P!%!8!8!: 1Q 1 +'
 112EFFF DIIK$./$2I2IITMaMaa%HI25diikD6H2I/  0'  2+
 G ! F//6Nqc4R^_/```!--***.1$))+2D.ED++	F  	Y//.Fqc,JVW/XXX	Ys   F4E? 2D DD E? -D +D,D DA9D >F4?E? D D D 	E<E7)D,*E7E
*E72E? 7E<<E? ?	F1F,!F$"F,'F4,F11F4r  c                   K   | j                   r;| j                          d{    | j                  j                  |       d{    d y7 -7 w)zProcess an audio chunk for STT transcription.

        Args:
            audio: Raw audio bytes to transcribe.

        Yields:
            Frame: None (actual transcription frames are pushed via internal processing).
        N)rU  start_processing_metricsr  r  )r=  r  s     r   run_sttzGoogleSTTService.run_stt  sK      //111%%))%000
 20s!    AA"AAAA
transcriptis_finalc                    K   y wr  r  )r=  r  r  r'   s       r   _handle_transcriptionz&GoogleSTTService._handle_transcription  s      	s   c                   K   	 |2 3 d{   }t        t        j                         dz        | j                  z
  | j                  kD  rt	        j
                  d        y|j                  sg|j                  D ]   }|j                  s|j                  d   j                  }|s-| j                         d   }|j                  rud| _        | j                  t        || j                  t               ||             d{    | j!                          d{    | j#                  |d|       d{    d| _        | j                  t%        || j                  t               ||             d{     y7 u7 7 k7 Q7 6 y# t&        $ r}t	        j
                  |  d	        d}~wt(        $ r%}| j+                  d
| |       d{  7    d}~ww xY ww)z(Process streaming recognition responses.Nr  z-Stream timeout reached in response processingr   T)result)r  r'   FzQ Stream aborted due to inactivity (no audio input). Reconnecting automatically...r  r  )r  r  rV  r  r   rz  resultsalternativesr  rx  r  r]  
push_framer   _user_idr   stop_processing_metricsr  r   r!   r  r  )r=  r  responser  r  primary_languager  s          r   r  z#GoogleSTTService._process_responses  s    @	"5 . .h		d*+d.E.EEI]I]]LL!PQ''&.. %F!.. !'!4!4Q!7!B!BJ% '+'?'?'A!'D$:>7"oo. * $ 0 2 0'-   #::<<<"88&%)%5 9    ;@7"oo5 * $ 0 2 0'-  ;%.* =M #6^  	 LL& 0 1  	//.Fqc,JVW/XXX 		s   G"F F
E?F
AF G" B F  FF FF 4F5A F 5F6	F ?F
F F F F 
F G"	GF..G:GGGGG"r  ).r$  r%  r&  r'  r  Settingsr(  r  r   rA  r   r   r)  r  floatrQ  r*  rs  r   r
   rv  rx  r}  r  dictr   r  r   r  r   r  r   r  r  r|  r{  r  r  bytesr	   r   r  r   r  r  __classcell__)rq  s   @r   r,  r,    s    !H   O7"i 7"x &**. %)(,04,;~e c]~e #3-	~e
 ~e c]~e %~e ,-~e #5/~e@d DXX5N DSVY]^aYbSb DT#Y "RT(^ R(&,= &$sCx. &P ! !!+ ! /3#7;48/3+/3715157;"&I+ DN+I+ }	I+
 '/tnI+ $,D>I+ 'tnI+ #4.I+ #+4.I+ !)I+ !)I+ '/tnI+ 3-I+ 
I+V#7J:!F"YH5 ^E4K-H  IM)-9A# 
Br  r,  )Cr'  r  r`  osr  r  dataclassesr   r   (pipecat.utils.tracing.service_decoratorsr   environtypingr   r	   r
   r   r   logurur   pydanticr   r   r   pipecat.frames.framesr   r   r   r   r   r   r  r   r   r   r   pipecat.services.stt_latencyr   pipecat.services.stt_servicer   pipecat.transcriptions.languager   r   pipecat.utils.timer   google.api_core.client_optionsr    google.api_core.exceptionsr!   google.authr"   google.auth.exceptionsr#   google.cloudr$   google.cloud.speech_v2.typesr%   google.oauth2r&   ModuleNotFoundErrorr  errorr  r)  r  r  r,  r  r  r   <module>r     s     	   ( ? *1

% & = =  6 6  ` _ 8 3 F /,<2#6&9-hIh hI8C= hIV	 $^ $^ $^Nk	z k	w
  ,FLL;qc"#FLL 	T &qc*
++,s   	*C D2DD