Azure 音频耳语(预览)示例

注意:有一个更新版本的 openai 库可用。请参阅 https://github.com/openai/openai-python/discussions/742

此示例展示了如何使用 Azure OpenAI Whisper 模型转录音频文件。

设置

首先,我们安装必要的依赖项。

! pip install "openai>=0.28.1,<1.0.0"
! pip install python-dotenv

接下来,我们将导入库并配置 Python OpenAI SDK 以与 Azure OpenAI 服务配合使用。

注意:在此示例中,我们通过在代码中设置变量来配置库以使用 Azure API。对于开发,请考虑改用设置环境变量:

OPENAI_API_BASE
OPENAI_API_KEY
OPENAI_API_TYPE
OPENAI_API_VERSION
import os
import dotenv
import openai

dotenv.load_dotenv()
True

要正确访问 Azure OpenAI 服务,我们需要在 Azure 门户 上创建相应的资源(您可以在 Microsoft Docs 中查看详细的操作指南)。

创建资源后,我们需要使用的第一项是其终结点。您可以从“资源管理”下的“密钥和终结点”部分获取终结点。有了这些信息,我们将使用此信息设置 SDK:

openai.api_base = os.environ["OPENAI_API_BASE"]

# 支持 Whisper 的最低 API 版本
openai.api_version = "2023-09-01-preview"

# 输入用于 Whisper 模型的 deployment_id
deployment_id = "<deployment-id-for-your-whisper-model>"

身份验证

Azure OpenAI 服务支持多种身份验证机制,包括 API 密钥和 Azure 凭据。

# 如果使用 Azure Active Directory 身份验证,则设置为 True
use_azure_active_directory = False

使用 API 密钥进行身份验证

要设置 OpenAI SDK 以使用 Azure API 密钥,我们需要将 api_type 设置为 azure,并将 api_key 设置为与您的终结点关联的密钥(您可以在 Azure 门户 的“资源管理”下的“密钥和终结点”中找到此密钥)。

if not use_azure_active_directory:
    openai.api_type = 'azure'
    openai.api_key = os.environ["OPENAI_API_KEY"]

使用 Azure Active Directory 进行身份验证

现在让我们看看如何通过 Microsoft Active Directory 身份验证获取密钥。

from azure.identity import DefaultAzureCredential

if use_azure_active_directory:
    default_credential = DefaultAzureCredential()
    token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

    openai.api_type = 'azure_ad'
    openai.api_key = token.token

令牌在一段时间内有效,之后会过期。为了确保每次请求都发送有效的令牌,您可以通过挂钩到 requests.auth 来刷新过期的令牌:

import typing
import time
import requests

if typing.TYPE_CHECKING:
    from azure.core.credentials import TokenCredential

class TokenRefresh(requests.auth.AuthBase):

    def __init__(self, credential: "TokenCredential", scopes: typing.List[str]) -> None:
        self.credential = credential
        self.scopes = scopes
        self.cached_token: typing.Optional[str] = None

    def __call__(self, req):
        if not self.cached_token or self.cached_token.expires_on - time.time() < 300:
            self.cached_token = self.credential.get_token(*self.scopes)
        req.headers["Authorization"] = f"Bearer {self.cached_token.token}"
        return req

if use_azure_active_directory:
    session = requests.Session()
    session.auth = TokenRefresh(default_credential, ["https://cognitiveservices.azure.com/.default"])

    openai.requestssession = session

音频转录

音频转录,也称为语音到文本,是将口语转换为文本的过程。使用 openai.Audio.transcribe 方法将音频文件流转录为文本。

您可以从 GitHub 上的 Azure AI Speech SDK 存储库 获取示例音频文件。

# 下载示例音频文件
import requests

sample_audio_url = "https://github.com/Azure-Samples/cognitive-services-speech-sdk/raw/master/sampledata/audiofiles/wikipediaOcelot.wav"
audio_file = requests.get(sample_audio_url)
with open("wikipediaOcelot.wav", "wb") as f:
    f.write(audio_file.content)
transcription = openai.Audio.transcribe(
    file=open("wikipediaOcelot.wav", "rb"),
    model="whisper-1",
    deployment_id=deployment_id,
)
print(transcription.text)