Я использую Azure AI Speech (ранее Azure Cognitive Services), в частности функцию преобразования текста в речь (TTS) в приложении Python Azure Function (Linux). Однако когда мое приложение-функция запущено и пытается вызвать службу речи AI, оно выдает следующую ошибку:
Connection failed (no connection to the remote host). Internal error: 1. Error details: Failed with error: WS_OPEN_ERROR_UNDERLYING_IO_OPEN_FAILED wss://eastus.tts.speech.microsoft.com/cognitiveservices/websocket/v1 X-ConnectionId: 45e9f87a28fa40ba981221cb55f6fc15 USP state: Sending. Received audio size: 0 bytes.
Мой код выглядит следующим образом:
try:
file_url = None
speech_config = speechsdk.SpeechConfig(
subscription=my_azure_ai_speech_api_key,
region = "eastus"
)
local_audio_path = f"/tmp/{filename}"
ensure_directory_exists(local_audio_path)
audio_config = speechsdk.audio.AudioOutputConfig(filename=local_audio_path)
synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
result = synthesizer.speak_text_async(text).get()
if result.reason == speechsdk.ResultReason.Canceled:
cancellation_details = result.cancellation_details
cancellation_reason = cancellation_details.reason
cancellation_error = ""
if cancellation_details.reason == speechsdk.CancellationReason.Error:
cancellation_error = cancellation_details.error_details
# Logic to log error here, this is actually where the error occurs that I mentioned above
return
with open(local_audio_path, "rb") as audio_file:
audio_data = audio_file.read()
# Logic to write the audio file to my Azure Blob Storage here
# Logic to remove the local file here
return file_url
except Exception as e:
# Logic to log error here
Я занимаюсь разработкой на компьютере под управлением Windows, и локально приложение Azure Function работает нормально и успешно вызывает службу речи AI. Эта проблема возникает только в облаке Azure с развернутым приложением-функцией Azure. Я уже пытался искать решения, и мне предлагалось установить OpenSSL 1.1 в моей среде приложения-функции, поэтому я создал этот сценарий запуска (startup.sh):
#!/bin/bash
# Log start of script
echo "Starting startup script"
# Update package lists
echo "Updating package lists"
apt-get update
# Install dependencies
echo "Installing dependencies"
apt-get install -y build-essential libssl-dev ca-certificates libasound2 wget
# Install OpenSSL 1.1
echo "Installing OpenSSL 1.1"
wget http://security.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2.19_amd64.deb
dpkg -i libssl1.1_1.1.1f-1ubuntu2.19_amd64.deb
# Verify installations
echo "Verifying OpenSSL installation"
openssl version
# Log end of script
echo "Startup script completed"
Затем я добавил эти переменные среды в свое приложение-функцию:
WEBSITE_STARTUP_SCRIPT=startup.sh
WEBSITE_RUN_FROM_PACKAGE=1
Но у меня все еще та же проблема. Помимо вышеперечисленного, я уже:
Согласно коду ошибки невозможно подключиться к TTS (перевести текст в речь)
Код:
Я использовал путь к локальному каталогу, чтобы сохранить преобразованный из текста в речь звук в файл output.wav в приведенном ниже коде.
import os
import azure.functions as func
import azure.cognitiveservices.speech as speechsdk
import logging
import traceback
def ensure_directory_exists(path):
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
app = func.FunctionApp()
@app.function_name(name = "HttpTriggerFunction")
@app.route(route = "tts", methods=["GET", "POST"])
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
text = req.params.get('text')
if not text:
try:
req_body = req.get_json()
except ValueError:
pass
else:
text = req_body.get('text')
if not text:
return func.HttpResponse(
"Please pass a text on the query string or in the request body",
status_code=400
)
try:
my_azure_ai_speech_api_key = "<speech_key>"
region = "<speech_region>"
speech_config = speechsdk.SpeechConfig(
subscription=my_azure_ai_speech_api_key,
region=region
)
local_audio_path = r"C:/Users/kamali/Documents/xxxxxx/output.wav"
ensure_directory_exists(local_audio_path)
audio_config = speechsdk.audio.AudioOutputConfig(filename=local_audio_path)
synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
result = synthesizer.speak_text_async(text).get()
if result.reason == speechsdk.ResultReason.Canceled:
cancellation_details = result.cancellation_details
logging.error(f"Speech synthesis canceled: {cancellation_details.reason}")
if cancellation_details.reason == speechsdk.CancellationReason.Error:
logging.error(f"Error details: {cancellation_details.error_details}")
return func.HttpResponse(
"Speech synthesis canceled",
status_code=500
)
with open(local_audio_path, "rb") as audio_file:
audio_data = audio_file.read()
return func.HttpResponse("File generated successfully", status_code=200)
except Exception as e:
logging.error(f"Exception: {str(e)}")
logging.error(f"Traceback: {traceback.format_exc()}")
return func.HttpResponse("An error occurred", status_code=500)
требования.txt:
azure-functions
azure-cognitiveservices-speech
Локальный выход:
Я получил приведенный ниже вывод в браузере с URL-адресом вывода функции триггера HTTP.
http://localhost:7071/api/tts?text=Hello World
Выход терминала VS Code:
Я получил результат. wav-файл, как показано ниже.
Перед развертыванием вышеуказанного проекта в приложении-функции Azure я обновил приведенный выше код, добавив local_audio_path = f"/tmp/output.wav"
в приведенный ниже код, который отлично работал у меня после развертывания в приложении-функции Azure.
import azure.functions as func
import azure.cognitiveservices.speech as speechsdk
import logging
import traceback
app = func.FunctionApp()
@app.function_name(name = "HttpTriggerFunction")
@app.route(route = "tts", methods=["GET", "POST"])
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
text = req.params.get('text')
if not text:
try:
req_body = req.get_json()
except ValueError:
pass
else:
text = req_body.get('text')
if not text:
return func.HttpResponse(
"Please pass a text on the query string or in the request body",
status_code=400
)
try:
my_azure_ai_speech_api_key = "<speech_key>"
region = "<speech_region>"
speech_config = speechsdk.SpeechConfig(
subscription=my_azure_ai_speech_api_key,
region=region
)
local_audio_path = f"/tmp/output.wav"
audio_config = speechsdk.audio.AudioOutputConfig(filename=local_audio_path)
synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
result = synthesizer.speak_text_async(text).get()
if result.reason == speechsdk.ResultReason.Canceled:
cancellation_details = result.cancellation_details
logging.error(f"Speech synthesis canceled: {cancellation_details.reason}")
if cancellation_details.reason == speechsdk.CancellationReason.Error:
logging.error(f"Error details: {cancellation_details.error_details}")
return func.HttpResponse(
"Speech synthesis canceled",
status_code=500
)
with open(local_audio_path, "rb") as audio_file:
audio_data = audio_file.read()
return func.HttpResponse("File generated successfully", status_code=200)
except Exception as e:
logging.error(f"Exception: {str(e)}")
logging.error(f"Traceback: {traceback.format_exc()}")
return func.HttpResponse("An error occurred", status_code=500)
Я развернул приведенный выше код в приложении «Функция Azure» и получил приведенный ниже вывод на портале Azure.
Спасибо, Дасари. Проблема решена. Проблема заключалась в том, что мое приложение-функция Azure не могло получить доступ к ресурсу речи Azure AI из-за конфигурации подсети. У меня была включена конечная точка службы «Microsoft.CognitiveServices». Я отключил его, и теперь приложение «Функция Azure» может выполнять вызов ресурса Azure AI Speech.
@Robin Я рад узнать, что проблема решена.
Используйте TLS версии 1.2.