|
''' |
|
DALL-E image generation example for openai>1.2.3, saves requested images as files |
|
-- not a code utility, has no input or return |
|
|
|
# example pydantic models returned by client.images.generate(**img_params): |
|
## - when called with "response_format": "url": |
|
images_response = ImagesResponse(created=1699713836, data=[Image(b64_json=None, revised_prompt=None, url='https://oaidalleapiprodscus.blob.core.windows.net/private/org-abcd/user-abcd/img-12345.png?st=2023-11-11T13%3A43%3A56Z&se=2023-11-11T15%3A43%3A56Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-11-10T21%3A41%3A11Z&ske=2023-11-11T21%3A41%3A11Z&sks=b&skv=2021-08-06&sig=%2BUjl3f6Vdz3u0oRSuERKPzPhFRf7qO8RjwSPGsrQ/d8%3D')]) |
|
|
|
requires: |
|
pip install --upgrade openai |
|
pip install pillow |
|
''' |
|
import os |
|
from io import BytesIO |
|
import openai |
|
from datetime import datetime |
|
import base64 |
|
import requests |
|
from PIL import Image |
|
from prompts import image_style_prompt |
|
from dotenv import load_dotenv |
|
load_dotenv() |
|
|
|
api_key = os.getenv("OPENAI_API_KEY") |
|
|
|
os.environ["OPENAI_API_KEY"] = api_key |
|
|
|
def old_package(version, minimum): |
|
version_parts = list(map(int, version.split("."))) |
|
minimum_parts = list(map(int, minimum.split("."))) |
|
return version_parts < minimum_parts |
|
|
|
if old_package(openai.__version__, "1.2.3"): |
|
raise ValueError(f"Error: OpenAI version {openai.__version__}" |
|
" is less than the minimum version 1.2.3\n\n" |
|
">>You should run 'pip install --upgrade openai')") |
|
|
|
from openai import OpenAI |
|
|
|
client = OpenAI() |
|
|
|
|
|
|
|
def generate_DALLE_images(user_prompt, path, filename): |
|
|
|
prompt = ( |
|
f"Subject: {user_prompt} " |
|
f"Style: {image_style_prompt}" |
|
) |
|
|
|
image_params = { |
|
"model": "dall-e-3", |
|
"n": 1, |
|
"size": "1024x1024", |
|
"prompt": prompt, |
|
"user": "myName", |
|
} |
|
|
|
|
|
|
|
image_params.update({"response_format": "b64_json"}) |
|
|
|
|
|
image_params.update({"model": "dall-e-3"}) |
|
image_params.update({"size": "1792x1024"}) |
|
|
|
|
|
|
|
print(f'Generating image {filename}') |
|
try: |
|
images_response = client.images.generate(**image_params) |
|
except openai.APIConnectionError as e: |
|
print("Server connection error: {e.__cause__}") |
|
raise |
|
except openai.RateLimitError as e: |
|
print(f"OpenAI RATE LIMIT error {e.status_code}: (e.response)") |
|
raise |
|
except openai.APIStatusError as e: |
|
print(f"OpenAI STATUS error {e.status_code}: (e.response)") |
|
raise |
|
except openai.BadRequestError as e: |
|
print(f"OpenAI BAD REQUEST error {e.status_code}: (e.response)") |
|
raise |
|
except Exception as e: |
|
print(f"An unexpected error occurred: {e}") |
|
raise |
|
|
|
|
|
|
|
|
|
img_filename = file_path = os.path.join(path, f'{filename}.png') |
|
|
|
|
|
revised_prompt = images_response.data[0].revised_prompt |
|
|
|
|
|
|
|
image_url_list = [] |
|
image_data_list = [] |
|
for image in images_response.data: |
|
image_url_list.append(image.model_dump()["url"]) |
|
image_data_list.append(image.model_dump()["b64_json"]) |
|
|
|
|
|
image_objects = [] |
|
|
|
|
|
if image_url_list and all(image_url_list): |
|
|
|
for i, url in enumerate(image_url_list): |
|
while True: |
|
try: |
|
print(f"getting URL: {url}") |
|
response = requests.get(url) |
|
response.raise_for_status() |
|
except requests.HTTPError as e: |
|
print(f"Failed to download image from {url}. Error: {e.response.status_code}") |
|
retry = input("Retry? (y/n): ") |
|
if retry.lower() in ["n", "no"]: |
|
raise |
|
else: |
|
continue |
|
break |
|
image_objects.append(Image.open(BytesIO(response.content))) |
|
image_objects[i].save(f"{img_filename}") |
|
print(f"Saving image to {img_filename}") |
|
elif image_data_list and all(image_data_list): |
|
|
|
for i, data in enumerate(image_data_list): |
|
image_objects.append(Image.open(BytesIO(base64.b64decode(data)))) |
|
image_objects[i].save(f"{img_filename}") |
|
print(f"Saving image to {img_filename}") |
|
else: |
|
print("No image data was obtained. Maybe bad code?") |
|
|
|
|
|
|
|
|