![]() |
| generated by DALL-E |
Wishing everyone a happy new year. Year 2023 is great for me because I learned much about OpenAI. I am involved in a live deployment with it, and involved in a handful of interesting user scenarios around it. On top of this, a copilot hackathon.
The image above is generated by DALL-E and following is the code.
1. Dependencies
python = "^3.10" pydantic-settings = "^2.1.0" openai = "^1.3.8"
2. Environment Parameters
OPENAI_AZURE_ENDPOINT="<your azure openai endpoint>" AZURE_OPENAI_API_KEY="<your azure openai secret>" OPENAI_API_VERSION="2023-12-01-preview" OPENAI_DALLE_MODEL="dalle"
Note:
OPENAI_API_VERSIONhas to be2023-12-01-previewotherwise you will get an exceptionopenai.NotFoundError: Error code: 404 - {'error': {'code': '404', 'message': 'Resource not found'}}dalleis the name of mydall-e-3deployment model. You need to change it to yours accordingly.
3. Pydantic Settings
from pydantic_settings import BaseSettings
class AzureOpenAISettings(BaseSettings):
openai_azure_endpoint: str
azure_openai_api_key: str
openai_api_version: str
openai_dalle_model: str
4. Code
from openai import AzureOpenAI
from openai.types import ImagesResponse
from common.settings import AzureOpenAISettings
def create_image(settings: AzureOpenAISettings, text: str) -> ImagesResponse:
client = AzureOpenAI(
api_key=settings.azure_openai_api_key,
azure_endpoint=settings.openai_azure_endpoint,
api_version=settings.openai_api_version,
)
return client.images.generate(model=settings.openai_dalle_model, prompt=text, n=1)
def generate_image(settings: AzureOpenAISettings, text: str):
import os
import requests
response = create_image(settings=settings, text=text)
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 = response.data[0].url
generated_image = requests.get(image_url).content # type: ignore
with open(image_path, "wb") as image_file:
image_file.write(generated_image)
if __name__ == "__main__":
settings = AzureOpenAISettings.model_validate({})
generate_image(
settings=settings,
text="Happy New Year, 2024, Wishing you all the best! From Dennis",
)
the generated image is stored in a
.images sub folder.As you can see that it is very simple. Once we get the
AzureOpenAI client initiated, we just need to function call to generate images.
Comments
Post a Comment