Azure OpenAIのDALLEやーる

# はじめに
Azure OpenAIのDALLEをやっていきます

https://learn.microsoft.com/ja-jp/azure/ai-services/openai/dall-e-quickstart?tabs=dalle3%2Ccommand-line&pivots=programming-language-python

# 導入

1．Azureポータルからdall-e-2とdall-e-3をデプロイします
2．エンドポイントとキーをコピペし、.envファイルを作成します

~~~
AZURE_OPENAI_ENDPOINT=https://xxxx.openai.azure.com/
AZURE_OPENAI_API_KEY=
~~~

3．コードを作成し、実行します

## DALLE3

### Python
~~~py
from openai import AzureOpenAI
import os
import requests
from PIL import Image
import json
from dotenv import load_dotenv

load_dotenv()

client = AzureOpenAI(
    api_version="2024-02-01",  
    api_key=os.environ["AZURE_OPENAI_API_KEY"],  
    azure_endpoint=os.environ['AZURE_OPENAI_ENDPOINT']
)

result = client.images.generate(
    model="dall-e-3", # the name of your DALL-E 3 deployment
    prompt="a close-up of a bear walking throughthe forest",
    n=1, #The number of images to generate. Only n=1 is supported for DALL-E 3.
    size="1024x1024",  # supported values are “1792x1024”, “1024x1024” and “1024x1792” 
    quality="standard", # Options are “hd” and “standard”; defaults to standard 
    style="vivid" # Options are “natural” and “vivid”; defaults to “vivid”
)

json_response = json.loads(result.model_dump_json())

# Set the directory for the stored image
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)

# Initialize the image path (note the filetype should be png)
image_path = os.path.join(image_dir, 'generated_image.png')

# Retrieve the generated image
image_url = json_response["data"][0]["url"]  # extract image URL from response
generated_image = requests.get(image_url).content  # download the image
with open(image_path, "wb") as image_file:
    image_file.write(generated_image)

# Display the image in the default image viewer
image = Image.open(image_path)
image.show()
~~~

![generated_image (1).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/85aad422-d129-ad18-e807-9dac114d0275.png)


### REST
~~~py
import requests
from PIL import Image
import os
from dotenv import load_dotenv

load_dotenv()

api_base = os.environ['AZURE_OPENAI_ENDPOINT']  # Enter your endpoint here
api_key = os.environ['AZURE_OPENAI_API_KEY']         # Enter your API key here

api_version = '2024-02-01'
url = f"{api_base}/openai/deployments/dall-e-3/images/generations?api-version={api_version}"
headers= { "api-key": api_key, "Content-Type": "application/json" }
body = {
    # Enter your prompt text here
    "prompt": "A multi-colored umbrella on the beach, disposable camera",
    "size": "1024x1024", # supported values are “1792x1024”, “1024x1024” and “1024x1792” 
    "n": 1, #The number of images to generate. Only n=1 is supported for DALL-E 3.
    "quality": "hd", # Options are “hd” and “standard”; defaults to standard 
    "style": "vivid" # Options are “natural” and “vivid”; defaults to “vivid”
}
json_response = requests.post(url, headers=headers, json=body).json()

# Set the directory for the stored image
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)

# Initialize the image path (note the filetype should be png)
image_path = os.path.join(image_dir, 'generated_image.png')

# Retrieve the generated image
image_url = json_response["data"][0]["url"]  # extract image URL from response
generated_image = requests.get(image_url).content  # download the image
with open(image_path, "wb") as image_file:
    image_file.write(generated_image)

# Display the image in the default image viewer
image = Image.open(image_path)
image.show()
~~~

![generated_image3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/83d68cfa-a652-8b62-eb43-457706d42277.png)

## DALLE2

### REST

~~~py
import time
import requests
from PIL import Image
import os
from dotenv import load_dotenv

load_dotenv()

api_base = os.environ['AZURE_OPENAI_ENDPOINT'] # Enter your endpoint here
api_key = os.environ['AZURE_OPENAI_API_KEY']         # Enter your API key here

# Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only)
api_version = '2023-06-01-preview'

# Define the prompt for the image generation
url = f"{api_base}openai/images/generations:submit?api-version={api_version}"
headers= { "api-key": api_key, "Content-Type": "application/json" }
body = {
    # Enter your prompt text here
    "prompt": "a multi-colored umbrella on the beach, disposable camera",  
    "size": "1024x1024",
    "n": 1
}
submission = requests.post(url, headers=headers, json=body)

# Call the API to generate the image and retrieve the response
operation_location = submission.headers['operation-location']
status = ""
while (status != "succeeded"):
    time.sleep(1)
    response = requests.get(operation_location, headers=headers)
    status = response.json()['status']
json_response = response.json()['result']

# Set the directory for the stored image
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)

# Initialize the image path (note the filetype should be png)
image_path = os.path.join(image_dir, 'generated_image.png')

# Retrieve the generated image
image_url = json_response["data"][0]["url"]  # extract image URL from response
generated_image = requests.get(image_url).content  # download the image
with open(image_path, "wb") as image_file:
    image_file.write(generated_image)

# Display the image in the default image viewer
image = Image.open(image_path)
image.show()
~~~
![generated_image4.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/9e531a5c-035d-5e33-a2ef-b72301de781f.png)

EditsやVariationsモードはなさそうです。 
お疲れ様でした。