
    F                         d Z ddlmZ ddlmZ ddlmZ ddlZddl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 ddlmZ ddlmZ dZdZej4                  d        Z G d de      Zy)zSpeech-to-text V2 client.    )absolute_import)division)unicode_literalsN)
list_pager)storage_util)apis)
exceptions)waiter)flag_validations)
properties)	resources)files)urllibspeechv2c              #      K   t        t        j                  j                  t              }|j                         }	 |j                  |        d |j                  |       y# |j                  |       w xY ww)zDContext manager to override an API's endpoint overrides for a while.N)getattrr   VALUESapi_endpoint_overrides	_API_NAMEGetSet)overrideendpoint_propertyold_endpoints      .lib/googlecloudsdk/api_lib/ml/speech/client.py_OverrideEndpointr   (   sg      ..	 #&&(,((#	,','s   9A9A# A9#A66A9c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 ZddZd Zd Zd Zd Zd Zd Zd ZddZ	 ddZ	 	 ddZ	 	 ddZ	 ddZ	 ddZ	 ddZy
)SpeechV2ClientzSpeech V2 API client wrappers.c                 >   t        j                  t        t              }t        j
                  j                  |j                        j                  | _	        t        j                  t        t              }t        j                         | _        | j                  j                  t        t               |j                  j                   j"                  |j                  j                   j$                  |j                  j                   j&                  d| _        || _        y )N)LINEAR16MULAWALAW)r   GetClientClassr   _API_VERSIONr   parseurlsplitBASE_URLnetloc_net_locGetMessagesModuler   Registry_resource_parserRegisterApiByNameExplicitDecodingConfigEncodingValueValuesEnumr!   r"   r#   _encoding_to_message	_messages)selfclient_classmessagess      r   __init__zSpeechV2Client.__init__9   s    &&y,?LLL)),*?*?@GGDM%%i>H%..0D++I|D ++CCLL00HHNN//GGLL!D DN    c                     t        dj                  || j                              5  t        j                  t
        t              cd d d        S # 1 sw Y   y xY w)Nzhttps://{}-{}/)r   formatr*   r   GetClientInstancer   r%   r3   locations     r   _GetClientForLocationz$SpeechV2Client._GetClientForLocationI   s9    	+228T]]K	L##I|< 
M	L	Ls   AAc                 8    | j                  |      j                  S N)r=   projects_locations_recognizersr;   s     r   _RecognizerServiceForLocationz,SpeechV2Client._RecognizerServiceForLocationM   s    %%h/NNNr7   c                 8    | j                  |      j                  S r?   )r=   projects_locations_operationsr;   s     r   _OperationsServiceForLocationz,SpeechV2Client._OperationsServiceForLocationP   s    %%h/MMMr7   c                 8    | j                  |      j                  S r?   )r=   projects_locationsr;   s     r   _LocationsServiceForLocationz+SpeechV2Client._LocationsServiceForLocationS   s    %%h/BBBr7   c                 r   | j                   j                  |      }||_        ||_        ||_        | j                   j                  |j                  d      j                         |j                         |      }| j                  |j                         j                               j                  |      S )z9Call API CreateRecognizer method with provided arguments.)displayNamezspeech.projects.locations)parent_collection)parentrecognizerId
recognizerr<   )r2   
RecognizermodellanguageCodesdefaultRecognitionConfig/SpeechProjectsLocationsRecognizersCreateRequestParentRelativeNameNamerA   Create)r3   resourcedisplay_namerP   language_codesrecognition_configrM   requests           r   CreateRecognizerzSpeechV2Client.CreateRecognizerV   s     **|*DJJ-J*<J'nnLL9  

,.]]_ M G --"'') . fWor7   c                     | j                   j                  |j                               }| j                  |j	                         j                               j                  |      S NnamerN   )r2   ,SpeechProjectsLocationsRecognizersGetRequestrU   rA   rT   rV   r   r3   rX   r\   s      r   GetRecognizerzSpeechV2Client.GetRecognizerq   s^    nnII""$ J G --"'') . 	c'lr7   c                     | j                   j                  |j                               }| j                  |j	                         j                               j                  |      S r_   )r2   /SpeechProjectsLocationsRecognizersDeleteRequestrU   rA   rT   rV   Deleterc   s      r   DeleteRecognizerzSpeechV2Client.DeleteRecognizery   s^    nnLL""$ M G --"'') . fWor7   Nc                     | j                   j                  |j                               }|r||_        t	        j
                  | j                  |j                               ||d|d      S )N)rK   pageSizerecognizerslimitbatch_size_attribute
batch_sizefield)r2   -SpeechProjectsLocationsRecognizersListRequestrU   	page_sizer   YieldFromListrA   rV   )r3   location_resourcerm   rr   r\   s        r   ListRecognizerszSpeechV2Client.ListRecognizers   so    nnJJ --/ K G #g##**+<+A+A+CD' r7   c                    | j                   j                         }|||_        |j                  d       |||_        |j                  d       |||_        |j                  d       ||_        | j                   j                  |j                         |dj                  |            }| j                  |j                         j                               j                  |      S )z9Call API UpdateRecognizer method with provided arguments.rY   rP   rZ   ,)ra   rM   
updateMaskrN   )r2   rO   rI   appendrP   rQ   rR   .SpeechProjectsLocationsRecognizersPatchRequestrU   joinrA   rT   rV   Patch)	r3   rX   rY   rP   rZ   r[   update_maskrM   r\   s	            r   UpdateRecognizerzSpeechV2Client.UpdateRecognizer   s     **,J+j(j!!!/j)**<J'nnKK""$88K( L G
 --"'') . eGnr7   c                    | j                   j                         }t        j                  j	                  |      rt        j                  |      |_        n&t        j                  j                  |      r||_        | j                  |j                         j                               }||_        dj!                  |      |_        | j                   j%                  ||j'                               }|j)                  |      S )z2Call API Recognize method with provided arguments.rN   rw   )recognizeRequestrM   )r2   RecognizeRequestospathisfiler   ReadBinaryFileContentscontentr   ObjectReferenceIsStorageUrlurirA   rT   rV   configr{   
configMask2SpeechProjectsLocationsRecognizersRecognizeRequestrU   	Recognize)r3   rX   audior[   r}   recognize_reqrecognizer_servicer\   s           r   RunShortzSpeechV2Client.RunShort   s     NN335M	ww~~e#::5Am		%	%	2	25	9m;;"'') <  .M"xx4MnnOO&((* P G ''00r7   c                    | j                   j                  |      }| j                   j                  |j                         |g      }| j	                  |j                         j                               }||_        | j                   j                  | j                   j                               |_
        dj                  |      |_        |j                  |      S )z@Call API Recognize method with provided arguments in batch mode.)r   )rM   r   rN   )inlineResponseConfigrw   )r2   BatchRecognizeFileMetadataBatchRecognizeRequestrU   rA   rT   rV   r   RecognitionOutputConfigInlineOutputConfigrecognitionOutputConfigr{   r   BatchRecognize)r3   rX   r   r[   r}   batch_audio_metadatar   r   s           r   RunBatchzSpeechV2Client.RunBatch   s      >>DDDONN88((*#$ 9 M
 ;;"'') <  .M 	..!%!B!B!D 	/ 	
 )  #xx4M,,];;r7   c                 N    | j                   j                  |j                  d      S )z$Converts an Operation to a Resource.z$speech.projects.locations.operations)r-   ParseRelativeNamera   )r3   	operations     r   GetOperationRefzSpeechV2Client.GetOperationRef   s%      22> r7   c                     t        j                  | j                  |      | j                  |            }t        j                  |||dd      S )a  Waits for a Recognizer operation to complete.

    Polls the Speech Operation service until the operation completes, fails, or
      max_wait_ms elapses.

    Args:
      location: The location of the resource.
      operation_ref: A Resource created by GetOperationRef describing the
        Operation.
      message: The message to display to the user while they wait.

    Returns:
      An Endpoint entity.
    )result_serviceoperation_serviced   i N  )polleroperation_refmessagepre_start_sleep_msmax_wait_ms)r
   CloudOperationPollerrA   rD   WaitForr3   r<   r   r   r   s        r   WaitForRecognizerOperationz)SpeechV2Client.WaitForRecognizerOperation   sR     ((99(C<<XFF
 >># r7   c                     t        j                  | j                  |      d       }t        j                  |||d      S )a  Waits for a Batch Recognize operation to complete.

    Polls the Speech Operation service until the operation completes, fails, or
      max_wait_ms elapses.

    Args:
      location: The location of the resource.
      operation_ref: A Resource created by GetOperationRef describing the
        Operation.
      message: The message to display to the user while they wait.

    Returns:
      An Endpoint entity.
    c                     | S r?    )xs    r   <lambda>z?SpeechV2Client.WaitForBatchRecognizeOperation.<locals>.<lambda>  s    !r7   i \&)r   wait_ceiling_ms)r
   CloudOperationPollerNoResourcesrD   r   r   s        r   WaitForBatchRecognizeOperationz-SpeechV2Client.WaitForBatchRecognizeOperation  sD     33**84F
 >> 	 r7   c                     | j                   j                  |j                               }| j                  |j	                               j                  |      S r_   )r2   !SpeechProjectsLocationsGetRequestrU   rG   rV   r   )r3   rt   r\   s      r   GetLocationzSpeechV2Client.GetLocation(  sV    nn>>++- ? G ,,"'') - 	c'lr7   c                    | j                   j                  t        j                  j                  j
                  j                               }|r||_        |r||_        t        j                  | j                  d      ||d|d      S )Nr`   globalrj   	locationsrl   )r2   "SpeechProjectsLocationsListRequestr   r   coreprojectr   filterrr   r   rs   rG   )r3   
filter_strrm   rr   r\   s        r   ListLocationszSpeechV2Client.ListLocations0  s    nn??##++//1 @ G !gn#g##))(3' r7   c                     | j                   j                         }|||_        |||_        |||fS ||j	                  d       ||j	                  d       ||fS )zUcreates a recognition config object and initializes it with model and language codes.rP   rZ   )r2   RecognitionConfigrP   rQ   ry   )r3   rP   rZ   r}   r[   s        r   InitializeRecognitionConfigz*SpeechV2Client.InitializeRecognitionConfigA  sz     99;!&!)7&,,!!)*{**r7   c                 l    | j                  ||j                  |j                  |j                  ||      S )N)default_to_auto_decoding_configr}   )*_InitializeDecodingConfigRecognizerCommandencodingsample_rateaudio_channel_count)r3   r[   argsr   r}   s        r    InitializeDecodingConfigFromArgsz/SpeechV2Client.InitializeDecodingConfigFromArgsT  s>     ::  (G ;  r7   c                    ||dk(  r | j                   j                         |_        n|t        j                  v rd| j                   j                         |_        | j                  |   |j                  _        |||j                  _	        |I||j                  _
        n7t        j                  dd      |r| j                   j                         |_        |||fS |dk(  r|j                  d       n7|t        j                  v r|j                  d       n|r|j                  d       |M|j                  | j                   j                         |_        ||j                  _	        |j                  d       |M|j                  | j                   j                         |_        ||j                  _
        |j                  d       ||fS )zkInitializes encoding type based on auto (or explicit decoding option), sample rate and audio channel count.AUTOz
--encodingz;[--encoding] must be set to LINEAR16, MULAW, ALAW, or AUTO.auto_decoding_configexplicit_decoding_configz*explicit_decoding_config.sample_rate_hertzz,explicit_decoding_config.audio_channel_count)r2   AutoDetectDecodingConfigautoDecodingConfigr   EXPLICIT_ENCODING_OPTIONSr/   explicitDecodingConfigr1   r   sampleRateHertzaudioChannelCountr	   InvalidArgumentExceptionry   )r3   r[   r   r   r   r   r}   s          r   r   z9SpeechV2Client._InitializeDecodingConfigRecognizerCommande  s    	V	NN335 	- 'AAANN113 	1
 %%h/ 	11: " 
3
3
C *! 
3
3
E 11I
 	
 
)
..
1
1
3 + ,,6/0	%??	?34	(/0		2	2	:NN113 	1 CN//?EF&		2	2	:NN113 	1  //A GH{**r7   c                 f    | j                  |j                  |j                  |j                  |      S )z&Initializes PhraseSets based on hints.)+_InitializeAdaptationConfigRecognizeRequesthint_phraseshint_phrase_sets
hint_boost)r3   r   r}   s      r   "InitializeAdaptationConfigFromArgsz1SpeechV2Client.InitializeAdaptationConfigFromArgs  s0     ;;400$//; r7   c           	         g }|rs| j                   j                  |D cg c]  }| j                   j                  |d      ! c}|      }| j                   j                  |      }|j	                  |       |r4|D ]/  }	| j                   j                  |	      }
|j	                  |
       1 | j                   j                  |      }||j	                  d       ||fS c c}w )z8Initializes PhraseSets based on phrases and phrase sets.      @)valueboost)phrasesr   )inlinePhraseSet)	phraseSet)
phraseSets
adaptation)r2   	PhraseSetPhraseAdaptationPhraseSetry   SpeechAdaptation)r3   r   r   r   r}   speech_adaptation_phrase_setshint_phraseinline_phrase_setinline_adaptation_phrase_sethint_phrase_setadaptation_phrase_setspeech_adaptation_configs               r   r   z:SpeechV2Client._InitializeAdaptationConfigRecognizeRequest  s    %'!..22 ".!-+ nn##+S#A!-  3  &*^^%G%G+ &H &" $**+GH-/ $ B B% !C !
 	&,,-BC	 .  $~~>>0  ?   &#[001s   $C!c                    | j                   j                         }g }|j                  "|j                  |_        |j	                  d       |j
                  "|j
                  |_        |j	                  d       |j                  "|j                  |_        |j	                  d       |j                  "|j                  |_
        |j	                  d       |j                  "|j                  |_        |j	                  d       |j                  "|j                  |_        |j	                  d       |j                  d|j                   X| j                   j#                  |j                  |j                         |_        |j	                  d       |j	                  d	       |j&                  rA| j                   j                  j(                  j*                  |_        |j	                  d
       nL|j&                  @| j                   j                  j(                  j.                  |_        |j	                  d
       |j0                  "|j0                  |_        |j	                  d       ||j5                  |       ||fS )z.Collects features from the provided arguments.zfeatures.profanityFilterzfeatures.enableWordTimeOffsetszfeatures.enableWordConfidencez#features.enableAutomaticPunctuationz features.enableSpokenPunctuationzfeatures.enableSpokenEmojis)minSpeakerCountmaxSpeakerCountz*features.diarizationConfig.minSpeakerCountz*features.diarizationConfig.maxSpeakerCountzfeatures.multiChannelModezfeatures.maxAlternatives)r2   RecognitionFeaturesprofanity_filterprofanityFilterry   enable_word_time_offsetsenableWordTimeOffsetsenable_word_confidenceenableWordConfidenceenable_automatic_punctuationenableAutomaticPunctuationenable_spoken_punctuationenableSpokenPunctuationenable_spoken_emojisenableSpokenEmojismin_speaker_countmax_speaker_countSpeakerDiarizationConfigdiarizationConfigseparate_channel_recognitionMultiChannelModeValueValuesEnum SEPARATE_RECOGNITION_PER_CHANNELmultiChannelModeMULTI_CHANNEL_MODE_UNSPECIFIEDmax_alternativesmaxAlternativesextend)r3   r   r}   features_configinner_update_masks        r   InitializeASRFeaturesFromArgsz,SpeechV2Client.InitializeASRFeaturesFromArgs  sD    nn88:O((,(=(=o%9:$$0.2.K.Ko+?@"".-1-H-Ho*>?((4

+
+ 0 DE%%1040N0No-AB  ,+/+D+Do(<=*"". ..
1
1"44"44 2  ' KLKL((
..
,
,
L
L
m
m & :;		*	*	6
..
,
,
L
L
k
k & :;((,(=(=o%9:*+K''r7   )NN)NNN)FNr?   )r   N)__name__
__module____qualname____doc__r6   r=   rA   rD   rG   r]   rd   rh   ru   r~   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r7   r   r   r   6   s    & =ONC6B18<<86$ :>+. ',. ',F+V  IM 1J :(r7   r   )r  
__future__r   r   r   
contextlibr   apitools.base.pyr   googlecloudsdk.api_lib.storager   googlecloudsdk.api_lib.utilr   r	   r
   $googlecloudsdk.command_lib.ml.speechr   googlecloudsdk.corer   r   googlecloudsdk.core.utilr   	six.movesr   r   r%   contextmanagerr   objectr   r   r7   r   <module>r     sk      &  '  	 ' 7 , 2 . A * ) *  	 
( 
(](V ](r7   