跳到主要内容

Azure DALL·E 图像生成示例

nbviewer

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

本笔记本展示了如何使用Azure OpenAI服务生成图像。

设置

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

! pip install "openai>=0.28.1,<1.0.0"
# 我们需要请求来获取生成的图像。
! 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 the directory doesn't exist, create it
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))