Skip to content

Commit

Permalink
expanded the scope of the post
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverlabs committed Jan 9, 2024
1 parent 485abb5 commit c9656d9
Showing 1 changed file with 80 additions and 1 deletion.
81 changes: 80 additions & 1 deletion content/posts/2024-01-09.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,86 @@ You will need to set the following environment variables in your `.env` file:

{{< notice note >}} If you are using conda to manage your Python environments, some environment variables tend to be sticky, I had to add the following code to workaround it: `load_dotenv(find_dotenv(), override=True)`, which seems to have fixed the issue. {{< /notice >}}

## Authenticate to Azure OpenAI Service

The following code is used to authenticate to Azure OpenAI Service:

```python
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_KEY"),
api_version="2023-12-01-preview"
)
```

Make sure to use the latest API version, which is `2023-12-01-preview` at the time of writing.

## Generate an Image

The following code is used to generate an image using DALL-E in Azure OpenAI with Python:

```python
result = client.images.generate(
model="dalle3", # the name of your DALL-E 3 deployment
prompt=input("Enter a query: "),
n=1
)
```

You can also hardcode the prompt value instead of using the `input()` function.

## Parse the Response

The following code is used to parse the response from the Azure OpenaAI API:

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

## Get the Image

The following code is used to get the image from the response:

```python
# 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
```


## Save the Image

The following code is used to save the image to a file:

```python
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

The following code is used to display the image:

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

## Conclusion

That's it! You can now generate images using DALL-E in Azure OpenAI with Python using the latest API schema.

Happy coding with Python and Azure OpenAI Service!

🐳

0 comments on commit c9656d9

Please sign in to comment.