Azure DALL·E 图像生成示例
注意:OpenAI 库有一个更新的版本。请参阅 https://github.com/openai/openai-python/discussions/742
本笔记本展示了如何使用 Azure OpenAI 服务生成图像。
设置
首先,我们安装必要的依赖项。
! pip install "openai>=0.28.1,<1.0.0"
# 我们需要 requests 来检索生成的图像
! pip install requests
# 我们使用 Pillow 来显示生成的图像
! pip install pillow
# (可选)如果您想使用 Microsoft Active Directory
! pip install azure-identity
import os
import openai
此外,为了正确访问 Azure OpenAI 服务,我们需要在 Azure 门户 上创建相应的资源(您可以查阅 Microsoft Docs 中关于如何执行此操作的详细指南)。
创建资源后,我们需要使用的第一件事是其终结点。您可以通过查看“资源管理”部分下的“密钥和终结点”来获取终结点。有了这个,我们将使用此信息设置 SDK:
openai.api_base = '' # 在此处添加您的终结点
# 目前 DALL·E 仅受 2023-06-01-preview API 版本支持
openai.api_version = '2023-06-01-preview'
身份验证
Azure OpenAI 服务支持多种身份验证机制,包括 API 密钥和 Azure 凭据。
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 API。对于开发,请考虑改用环境变量:
OPENAI_API_BASE
OPENAI_API_KEY
OPENAI_API_TYPE
OPENAI_API_VERSION
使用 Microsoft 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
生成
设置和身份验证完成后,您现在可以生成 Azure OpenAI 服务上的图像并从返回的 URL 中检索它们。
1. 生成图像
此过程的第一步是实际生成图像:
generation_response = openai.Image.create(
prompt='A cyberpunk monkey hacker dreaming of a beautiful bunch of bananas, digital art',
size='1024x1024',
n=2
)
print(generation_response)
使用 Image.create
调用的响应,我们使用 requests
从 URL 下载。
import os
import requests
# 首先进行一些设置
image_dir = os.path.join(os.curdir, 'images')
# 如果目录不存在,则创建它
if not os.path.isdir(image_dir):
os.mkdir(image_dir)
# 在目录就位后,我们可以初始化图像路径(请注意文件类型应为 png)
image_path = os.path.join(image_dir, 'generated_image.png')
# 现在我们可以检索生成的图像
image_url = generation_response["data"][0]["url"] # 从响应中提取图像 URL
generated_image = requests.get(image_url).content # 下载图像
with open(image_path, "wb") as image_file:
image_file.write(generated_image)
下载图像后,我们使用 Pillow 库打开并显示它:
from PIL import Image
display(Image.open(image_path))