[docs]classHuggingFaceTextToSpeechModelInference(BaseTool):# type: ignore[override]"""HuggingFace Text-to-Speech Model Inference. Requirements: - Environment variable ``HUGGINGFACE_API_KEY`` must be set, or passed as a named parameter to the constructor. """name:str="openai_text_to_speech""""Name of the tool."""description:str="A wrapper around OpenAI Text-to-Speech API. """"Description of the tool."""model:str"""Model name."""file_extension:str"""File extension of the output audio file."""destination_dir:str"""Directory to save the output audio file."""file_namer:Callable[[],str]"""Function to generate unique file names."""api_url:strhuggingface_api_key:SecretStr_HUGGINGFACE_API_KEY_ENV_NAME:str="HUGGINGFACE_API_KEY"_HUGGINGFACE_API_URL_ROOT:str="https://api-inference.huggingface.co/models"def__init__(self,model:str,file_extension:str,*,destination_dir:str="./tts",file_naming_func:Literal["uuid","timestamp"]="uuid",huggingface_api_key:Optional[SecretStr]=None,_HUGGINGFACE_API_KEY_ENV_NAME:str="HUGGINGFACE_API_KEY",_HUGGINGFACE_API_URL_ROOT:str="https://api-inference.huggingface.co/models",)->None:ifnothuggingface_api_key:huggingface_api_key=SecretStr(os.getenv(_HUGGINGFACE_API_KEY_ENV_NAME,""))if(nothuggingface_api_keyornothuggingface_api_key.get_secret_value()orhuggingface_api_key.get_secret_value()==""):raiseValueError(f"'{_HUGGINGFACE_API_KEY_ENV_NAME}' must be or set or passed")iffile_naming_func=="uuid":file_namer=lambda:str(uuid.uuid4())# noqa: E731eliffile_naming_func=="timestamp":file_namer=lambda:str(int(datetime.now().timestamp()))# noqa: E731else:raiseValueError(f"Invalid value for 'file_naming_func': {file_naming_func}")super().__init__(# type: ignore[call-arg]model=model,file_extension=file_extension,api_url=f"{_HUGGINGFACE_API_URL_ROOT}/{model}",destination_dir=destination_dir,file_namer=file_namer,huggingface_api_key=huggingface_api_key,_HUGGINGFACE_API_KEY_ENV_NAME=_HUGGINGFACE_API_KEY_ENV_NAME,_HUGGINGFACE_API_URL_ROOT=_HUGGINGFACE_API_URL_ROOT,)def_run(self,query:str,run_manager:Optional[CallbackManagerForToolRun]=None,)->str:response=requests.post(self.api_url,headers={"Authorization":f"Bearer {self.huggingface_api_key.get_secret_value()}"},json={"inputs":query},)audio_bytes=response.contenttry:os.makedirs(self.destination_dir,exist_ok=True)exceptExceptionase:logger.error(f"Error creating directory '{self.destination_dir}': {e}")raiseoutput_file=os.path.join(self.destination_dir,f"{str(self.file_namer())}.{self.file_extension}",)try:withopen(output_file,mode="xb")asf:f.write(audio_bytes)exceptFileExistsError:raiseValueError("Output name must be unique")exceptExceptionase:logger.error(f"Error occurred while creating file: {e}")raisereturnoutput_file