[docs]classAzureCogsText2SpeechTool(BaseTool):# type: ignore[override]"""Tool that queries the Azure Cognitive Services Text2Speech API. In order to set this up, follow instructions at: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-text-to-speech?pivots=programming-language-python """azure_cogs_key:str=""#: :meta private:azure_cogs_region:str=""#: :meta private:speech_language:str="en-US"#: :meta private:speech_config:Any#: :meta private:name:str="azure_cognitive_services_text2speech"description:str=("A wrapper around Azure Cognitive Services Text2Speech. ""Useful for when you need to convert text to speech. ")@model_validator(mode="before")@classmethoddefvalidate_environment(cls,values:Dict)->Any:"""Validate that api key and endpoint exists in environment."""azure_cogs_key=get_from_dict_or_env(values,"azure_cogs_key","AZURE_COGS_KEY")azure_cogs_region=get_from_dict_or_env(values,"azure_cogs_region","AZURE_COGS_REGION")try:importazure.cognitiveservices.speechasspeechsdkvalues["speech_config"]=speechsdk.SpeechConfig(subscription=azure_cogs_key,region=azure_cogs_region)exceptImportError:raiseImportError("azure-cognitiveservices-speech is not installed. ""Run `pip install azure-cognitiveservices-speech` to install.")returnvaluesdef_text2speech(self,text:str,speech_language:str)->str:try:importazure.cognitiveservices.speechasspeechsdkexceptImportError:passself.speech_config.speech_synthesis_language=speech_languagespeech_synthesizer=speechsdk.SpeechSynthesizer(speech_config=self.speech_config,audio_config=None)result=speech_synthesizer.speak_text(text)ifresult.reason==speechsdk.ResultReason.SynthesizingAudioCompleted:stream=speechsdk.AudioDataStream(result)withtempfile.NamedTemporaryFile(mode="wb",suffix=".wav",delete=False)asf:stream.save_to_wav_file(f.name)returnf.nameelifresult.reason==speechsdk.ResultReason.Canceled:cancellation_details=result.cancellation_detailslogger.debug(f"Speech synthesis canceled: {cancellation_details.reason}")ifcancellation_details.reason==speechsdk.CancellationReason.Error:raiseRuntimeError(f"Speech synthesis error: {cancellation_details.error_details}")return"Speech synthesis canceled."else:returnf"Speech synthesis failed: {result.reason}"def_run(self,query:str,run_manager:Optional[CallbackManagerForToolRun]=None,)->str:"""Use the tool."""try:speech_file=self._text2speech(query,self.speech_language)returnspeech_fileexceptExceptionase:raiseRuntimeError(f"Error while running AzureCogsText2SpeechTool: {e}")