
    eiM                    N   d Z ddlmZ ddlmZmZmZmZ ddlZddl	m
Z ddlmZ dd	lmZ erdd
lmZ eddgz   Z G d dej                  Zg  eddd           eddd           eddd           eddd           eddd           eddd           eddd           ed dd!           ed"dd#           ed$dd%           ed&dd'           ed(dd)           ed*dd+           ed,dd-           ed.dd/           ed0dd1           ed2d3d4           ed5d6d7           ed2d8d9           ed:d;d<           ed=d;d>           ed?d;d@           edAdBdC           edDdEdF           edGdHdI           edJdKdL           edMdNdO           edPdNdQ           edRdNdS           edTdNdU           edVdNdW           edXdNdY           eddNdZ           ed[dNd\           ed]dNd^           ed_d`da           edbdcdd           edXdedf           ed2dgdh           edidjdk           edldmdn           edodpdq           eddrds           edRdtdu           edvdwdx           edydzd{           ed|d}d~           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           eddd           edddì           edddŬ           edddǬ           edddɬ           edddˬ           edddͬ           ed2ddά           edddЬ           ed]ddѬ           edddӬ           eddd֬           eddd٬           edddܬ           eddd߬           eddd           eddd          Ze                    d            d eD             Z G d dej                  Z G d de          Z G d dej                  Z G d dej                  Z G d de          Z
dS )a.  
The SpeechToText widget controls the speech recognition service of the
browser.

It wraps the HTML5 SpeechRecognition API.  See
https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition

This functionality is **experimental** and only supported by Chrome
and a few other browsers.  Checkout
https://caniuse.com/speech-recognition for a up to date list of
browsers supporting the SpeechRecognition Api. Or alternatively
https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition#Browser_compatibility

On some browsers, like Chrome, using Speech Recognition on a web page
involves a server-based recognition engine. Your audio is sent to a
web service for recognition processing, so it won't work
offline. Whether this is secure and confidential enough for your use
case is up to you to evaluate.
    )annotations)TYPE_CHECKINGClassVarMappingTypeN   )SpeechToText   )Widget)BUTTON_TYPES)Modellightdarkc                  z    e Zd Z ej        d          Z ej        d          Z ej        d          Zd ZdS )LanguagezA country like 'United States'doczX
        The bcp 47 code uniquely identifying the language. For example
        'en-US'.z<
        The overall language family. For example 'English'.c                6    | j          d| j         d| j         dS )Nz - z ())familycountrynameselfs    <lib/python3.11/site-packages/panel/widgets/speech_to_text.py__str__zLanguage.__str__2   s'    +>>$,>>$)>>>>    N)	__name__
__module____qualname__paramStringr   r   r   r    r   r   r   r   '   sw        el?@@@G5<    D U\ ? @ @ @F? ? ? ? ?r   r   zSouth Africa	Afrikaanszaf-ZA)r   r   r   AlgeriaArabiczar-DZBahrainzar-BHEgyptzar-EGIsraelzar-ILIraqzar-IQJordanzar-JOKuwaitzar-KWLebanonzar-LBMoroccozar-MAOmanzar-OMzPalestinian Territoryzar-PSQatarzar-QAzSaudi Arabiazar-SATunisiazar-TNUAEzar-AESpainBasquezeu-ESBulgaria	Bulgarianzbg-BGCatalanzca-ESzChina (Simp.)zChinese Mandarinzcmn-Hans-CNzHong Kong SAR (Trad.)zcmn-Hans-HKzTaiwan (Trad.)zcmn-Hant-TWz	Hong KongzChinese Cantonesezyue-Hant-HKCroatiaCroatianhr_HRzCzech RepublicCzechzcs-CZDenmarkDanishzda-DK	AustraliaEnglishzen-AUCanadazen-CAIndiazen-INIrelandzen-IEzNew Zealandzen-NZPhilippineszen-PHzen-ZAzUnited Kingdomzen-GBzUnited Stateszen-USIranFarsizfa-IRFranceFrenchzfr-FRFilipinozfil-PHGalicianzgl-ESGermanyGermanzde-DEGreeceGreekzel-GRFinlandFinnishzfi-FIHebrewzhe-ILHindizhi-INHungary	Hungarianzhu-HU	Indonesia
Indonesianzid-IDIceland	Icelandiczis-ISItalyItalianzit-ITSwitzerlandzit-CHJapanJapanesezja-JPKoreaKoreanzko-KR	Lithuania
Lithuanianzlt-LTMalaysia	Malaysianzms-MYNetherlandsDutchznl-NLNorway	Norwegianznb-NOPolandPolishzpl-PLBrazil
Portuguesezpt-BRPortugalzpt-PTRomaniaRomanianzro-RORussiaRussianzru-RUSerbiaSerbianzsr-RSSlovakiaSlovakzsk-SKSlovenia	Slovenianzsl-SI	ArgentinaSpanishzes-ARBoliviazes-BOChilezes-CLColombiazes-COz
Costa Ricazes-CRzDominican Republiczes-DOEcuadorzes-ECzEl Salvadorzes-SV	Guatemalazes-GTHonduraszes-HNu   Méxicozes-MX	Nicaraguazes-NIu   Panamázes-PAParaguayzes-PYu   Perúzes-PEzPuerto Ricozes-PRzes-ESUruguayzes-UYzes-US	Venezuelazes-VESwedenSwedishzsv-SEThailandThaizth-THTurkeyTurkishztr-TRUkraine	Ukrainianzuk-UAzViet Nam
Vietnamesezvi-VNZuluzzu-ZAc                    | j         S Nr   )xs    r   <lambda>r      s    QV r   )keyc                    g | ]	}|j         
S r#   r   ).0langs     r   
<listcomp>r      s    222$)222r   c                      e Zd ZdZ ej        d          Z ej        d          Z ej        dddd	          Z	d
 Z
dS )Grammarac  A set of words or patterns of words that we want the speech recognition service to recognize

    For example

    grammar = Grammar(
        src='#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige;',
        weight=0.7
    )

    Wraps the HTML SpeechGrammar API.
    See https://developer.mozilla.org/en-US/docs/Web/API/SpeechGrammar
    z
        A set of words or patterns of words that we want the
        recognition service to recognize. Defined using JSpeech
        Grammar Format. See https://www.w3.org/TR/jsgf/.r   z
        An uri pointing to the definition. If src is available it will
        be used. Otherwise uri. The uri will be loaded on the client
        side only.r
   g              ?g{Gz?uM   
       The weight of the grammar. A number in the range 0–1. Default is 1.)defaultboundsstepr   c                x    | j         r| j         | j        dS | j        r| j        | j        dS t          d          )zReturns the grammar as dictsrcweighturir   zOne of src or uri must be set)r   r   r   
ValueErrorr   s    r   	serializezGrammar.serialize   sI    8 	<8t{;;;8 	<8t{;;;8999r   N)r   r   r    __doc__r!   r"   r   r   Numberr   r   r#   r   r   r   r      s          %, < = = =C
 %,    C
 U\!JT HP Q Q QF: : : : :r   r   c                  (    e Zd ZdZddZddZd ZdS )GrammarLista  A list of Grammar objects containing words or patterns of words that we want the
    recognition service to recognize.

    Example:

    grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque ;'
    grammar_list = GrammarList()
    grammar_list.add_from_string(grammar, 1)

    Wraps the HTML 5 SpeechGrammarList API

    See https://developer.mozilla.org/en-US/docs/Web/API/SpeechGrammarList
    r   c                R    t          ||          }|                     |           |S )z
        Takes a src and weight and adds it to the GrammarList as a new
        Grammar object. The new Grammar object is returned.
        r   r   append)r   r   r   grammars       r   add_from_stringzGrammarList.add_from_string   s-    
 c&111Gr   c                R    t          ||          }|                     |           |S )z
        Takes a grammar present at a specific uri, and adds it to the
        GrammarList as a new Grammar object. The new Grammar object is
        returned.
        r   r   )r   r   r   r   s       r   add_from_urizGrammarList.add_from_uri   s-     c&111Gr   c                    d | D             S )z%Returns a list of serialized grammarsc                6    g | ]}|                                 S r#   )r   )r   r   s     r   r   z)GrammarList.serialize.<locals>.<listcomp>   s$    888!!##888r   r#   r   s    r   r   zGrammarList.serialize   s    8848888r   N)r   )r   r   r    r   r   r   r   r#   r   r   r   r      sU               9 9 9 9 9r   r   c                  \    e Zd ZdZ ej        ddd          Z ej        dd          ZdS )	RecognitionAlternativea
  The RecognitionAlternative represents a word or
    sentence that has been recognised by the speech recognition service.

    Wraps the HTML5 SpeechRecognitionAlternative API

    See https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognitionAlternative
    r   Tz
        A numeric estimate between 0 and 1 of how confident the speech recognition
        system is that the recognition is correct.)r   constantr   z;
        The transcript of the recognised word or sentence.r   r   N)	r   r   r    r   r!   r   
confidencer"   
transcriptr#   r   r   r   r      s]          Z$ E6 7 7 7J t 2> ? ? ?JJJr   r   c                      e Zd ZdZ ej        edd          Z ej        dd          Z	e
d             Ze
d             Zd	S )
RecognitionResultzThe Result represents a single recognition match, which may contain
    multiple RecognitionAlternative objects.

    Wraps the HTML5 SpeechRecognitionResult API.

    See https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognitionResult
    Tz,
        The list of the n-best alternatives)	item_typer   r   u   
        A Boolean that states whether this result is final (True) or
        not (False) — if so, then this is the final time this result
        will be returned; if not, then this result is an interim
        result, and may be updated later on.r   c                    |                                 }|                    dg           }g }|D ]!}|                    t          di |           "||d<    | di |S )z=
        Deserializes a serialized RecognitionResult
        alternativesr#   )copygetr   r   )clsresultr   _alternativesalternatives        r   create_from_dictz"RecognitionResult.create_from_dict  s|    
 zz."55' 	H 	HK  !7!F!F+!F!FGGGG!.~s}}V}}r   c                       fd|D             S )zG
        Deserializes a list of serialized RecognitionResults.
        c                :    g | ]}                     |          S r#   )r   )r   r   r   s     r   r   z6RecognitionResult.create_from_list.<locals>.<listcomp>  s'    CCC$$V,,CCCr   r#   )r   resultss   ` r   create_from_listz"RecognitionResult.create_from_list  s     
 DCCC7CCCCr   N)r   r   r    r   r!   Listr   r   Booleanis_finalclassmethodr   r   r#   r   r   r   r      s          5:(> T/ 0 0 0L u}d 10 1 1 1H 
 
 [
 D D [D D Dr   r   c                      e Zd ZU dZ ej        d          Z ej        d          Z ej        d          Z ej	        ddge
z   ddd	
          Z ej        dd          Z ej        dd          Z ej        ddd          Z ej        d          Z ej        ed          Z ej        ddd          Z ej	        ded          Z ej        dd          Z ej        dd           Z ej        dd!"          Z ej        dd#"          Z ej        dd$"          Z ej        dd%"          Z ej        dd&"          Z  ej        dd'd()          Z! ej        dd*"          Z"d+d,d+d+d-Z#d.e$d/<   e%Z&d0e$d1<    fd2Z'd<d3Z( ej)        d,d4          d5             Z* ej)        d6d4          d7             Z+e,d8             Z-e,d=d;            Z. xZ/S )>r	   a  
    The SpeechToText widget controls the speech recognition service of
    the browser.

    It wraps the HTML5 SpeechRecognition API.  See
    https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition

    Reference: https://panel.holoviz.org/reference/widgets/SpeechToText.html

    :Example:

    >>> SpeechToText(button_type="light")

    This functionality is **experimental** and only supported by
    Chrome and a few other browsers.  Checkout
    https://caniuse.com/speech-recognition for a up to date list of
    browsers supporting the SpeechRecognition Api. Or alternatively
    https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition#Browser_compatibility

    On some browsers, like Chrome, using Speech Recognition on a web
    page involves a server-based recognition engine. Your audio is
    sent to a web service for recognition processing, so it won't work
    offline. Whether this is secure and confidential enough for your
    use case is up to you to evaluate.
    z
        Stops the speech recognition service from listening to
        incoming audio, and doesn't attempt to return a
        RecognitionResult.r   z
        Starts the speech recognition service listening to incoming
        audio with intent to recognize grammars associated with the
        current SpeechRecognition.z
        Stops the speech recognition service from listening to
        incoming audio, and attempts to return a RecognitionResult
        using the audio captured so far. Tr   z
        The language of the current SpeechRecognition in BCP 47
        format. For example 'en-US'. If not specified, this defaults
        to the HTML lang attribute value, or the user agent's language
        setting if that isn't set either.  )r   objects
allow_Nonelabelr   Fz
        Controls whether continuous results are returned for each
        recognition, or only a single result. Defaults to False)r   r   z
        Controls whether interim results should be returned (True) or
        not (False.) Interim results are results that are not yet
        final (e.g. the RecognitionResult.is_final property is
        False).r
   )r
      z
        Sets the maximum number of RecognitionAlternatives provided
        per result.  A number between 1 and 5. The default value is
        1.)r   r   r   z
        Specifies the location of the speech recognition service used
        by the current SpeechRecognition to handle the actual
        recognition. The default is the user agent's default speech
        service.z
        A GrammarList object that represents the grammars that will be
        understood by the current SpeechRecognition service)class_r   zHide the ButtonzS
        If True no button is shown. If False a toggle Start/ Stop button is shown.)r   r   r   r   z
        The button styling.)r   r   r   zButton Text when not startedz
        The text to show on the button when the SpeechRecognition
        service is NOT started.  If '' a *muted microphone* icon is
        shown.)r   r   zButton Text when startedz
        The text to show on the button when the SpeechRecognition
        service is started. If '' a *muted microphone* icon is
        shown.z_
        Returns True if the Speech Recognition Service is started and
        False otherwise.r   zB
        Returns True if the Audio is started and False otherwise.zB
        Returns True if the Sound is started and False otherwise.zO
        Returns True if the the User has started speaking and False otherwise.z1
        The `results` as a list of Dictionaries.zLast Resultz
        The transcipt of the highest confidence RecognitionAlternative
        of the last RecognitionResult. Please note we strip the
        transcript for leading spaces.)r   r   r   zV
        List used to transfer the serialized grammars from server to
        browser.Ngrammars)r   	_grammarsr   valuez"ClassVar[Mapping[str, str | None]]_renamezClassVar[Type[Model]]_widget_typec                t     t                      j        di | | j        r|                                  d S d S )Nr#   )super__init__r   _update_grammars)r   params	__class__s     r   r   zSpeechToText.__init__  sL    ""6"""= 	$!!#####	$ 	$r   c                    d| j          dS )NzSpeechToText(name='z')r   )r   depths     r   __repr__zSpeechToText.__repr__  s     3TY2222r   )watchc                    t          j        |           5  | j        r| j                                        | _        ng | _        d d d            d S # 1 swxY w Y   d S r   )r!   edit_constantr   r   r   r   s    r   r   zSpeechToText._update_grammars  s     && 	$ 	$} $!%!8!8!:!:!#		$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$s   .AAAr   c                   t          j        |           5  | j        rFd| j        d         v r7| j        d         d         d         d                                         | _        nd| _        d d d            d S # 1 swxY w Y   d S )Nr   r   r   r   )r!   r   r   lstripr   r   s    r   _update_resultszSpeechToText._update_results  s      && 	  	 |  $,r2B B B"l2.~>qA,OWWYY


		  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 s   AA77A;>A;c                @    t                               | j                  S )zE
        Returns the results as a List of RecognitionResults
        )r   r   r   r   s    r   results_deserializedz!SpeechToText.results_deserialized  s    
 !11$,???r   returnstrc                   | j         sdS d}t          | j                   dz
  }t          t          | j                            D ]\  }}t          | j                   dk    r|d||z
   dz  }|d|j         dz  }t          |j                  D ]=\  }}t          |j                  dk    r	|d| d	z  }|d
|j        dd|j         dz  }>|dz  }|S )ze
        Returns the `results` formatted as html

        Convenience method for ease of use
        z
No resultsz*<div class="pn-speech-recognition-result">r
   z<h3>Result z</h3>z<span>Is Final: z</span><br/>z<h4>Alternative z</h4>z#
                <span>Confidence: z.2fzL</span>
                </br>
                <p>
                  <strong>z/</strong>
                </p>
                z</div>)	r   len	enumeratereversedr   r   r   r   r   )r   htmltotalindexr   index2r   s          r   results_as_htmlzSpeechToText.results_as_html  s7    | 	 <;DL!!A%&x0I'J'JKK 	 	ME64<  1$$8eEk8888DvDDDDD'01D'E'E 	 	#v*++a//<v<<<<D #.#9   '1	   	 	r   r   )r   r   )0r   r   r    r   r!   EventabortstartstopObjectSelectorLANGUAGE_CODESr   r   
continuousinterim_resultsIntegermax_alternativesr"   service_uriClassSelectorr   r   button_hider   button_typebutton_not_startedbutton_startedstartedaudio_startedsound_startedspeech_startedr   r   r   r   r   __annotations___BkSpeechToTextr   r   r   dependsr   r   propertyr   r   __classcell__)r   s   @r   r	   r	     s         4 EK    E
 EK & ' ' 'E
 5; , - - -D
  5RD>4I+/z H/0 0 0D u 3C D D DJ $emE 8   O %u}Qv D   
 %, $   K #u"+ <? @ @ @H  %-5F MV W W WK '%&w S      K &,J Q   
 "U\(B I   N
 emT 0   G "EM4 6E F F FM "EM4 6E F F FM #U]D 7R S S SN ej$ -4 5 5 5G EL$m B* + + +E
 
D /   I
 z4$3 3G     +:L9999$ $ $ $ $
3 3 3 3
 U]:T***$ $ +*$ U]9D)))    *)  @ @ X@    X    r   r	   )r   
__future__r   typingr   r   r   r   r!   models.speech_to_textr	   r
  baser   buttonr   bokeh.modelr   Parameterizedr   	LANGUAGESsortr   r   listr   r   r   r#   r   r   <module>r     s\   ( # " " " " "             C C C C C C                   "!!!!!!Wf--? ? ? ? ?u" ? ? ? ZH^KgFFFZHYxg>>>Z HYxg>>>Z HWXG<<<	Z
 HXhW===Z HVH7;;;Z HXhW===Z HXhW===Z HYxg>>>Z HYxg>>>Z HVH7;;;Z H,XGLLLZ HWXG<<<Z H^H7CCCZ HYxg>>>Z  HU8':::!Z" HWXG<<<#Z$ HZ'BBB%Z& HWYW==='Z( H_-?mTTT)Z* H,5Gm\\\+Z, H%.@}UUU-Z. H[)<=QQQ/Z0 HYz@@@1Z2 H%gGDDD3Z4 HYxg>>>5Z6 H[AAA7Z8 HXig>>>9Z: HWYW===;Z< HYyw???=Z> H]97CCC?Z@ H]97CCCAZB H^IGDDDCZD H%igFFFEZF H_YWEEEGZH HVG':::IZJ HXhW===KZL H]:HEEEMZN HWZg>>>OZP HYxg>>>QZR HXgG<<<SZT HYyw???UZV HXhW===WZX HWW7;;;YZZ HY{AAA[Z\ H[GDDD]Z^ HY{AAA_Z` HWYW===aZb H]97CCCcZd HWZg>>>eZf HWXG<<<gZh H[GDDDiZj HZ'BBBkZl H]7AAAmZn HXk@@@oZp HXhW===qZr HXlAAAsZt HZ7CCCuZv HYz@@@wZx HXig>>>yZz HXig>>>{Z| HZw???}Z~ HZ'BBBZ@ H[AAAAZB HYyw???CZD HWYW===EZF HZ	@@@GZH H\)'BBBIZJ H))'JJJKZL HYyw???MZN H]97CCCOZP H[AAAQZR HZ	@@@SZT HYyw???UZV H[AAAWZX HYyw???YZZ HZ	@@@[Z\ HWYW===]Z^ H]97CCC_Z` HWYW===aZb HYyw???cZd H_YWEEEeZf H[AAAgZh HXig>>>iZj HZW===kZl HXig>>>mZn HY{AAAoZp HZ7CCCqZr H^FAAAsZ	v 
## $ $ $22	222!: !: !: !: !:e! !: !: !:H$9 $9 $9 $9 $9$ $9 $9 $9N? ? ? ? ?U0 ? ? ?"$D $D $D $D $D+ $D $D $DNu u u u u6 u u u u ur   