-
Notifications
You must be signed in to change notification settings - Fork 699
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: update image generator to dalle3
- Loading branch information
Showing
2 changed files
with
14 additions
and
74 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,59 +1,21 @@ | ||
import os | ||
import json | ||
|
||
import openai | ||
from pathlib import Path | ||
from base64 import b64decode | ||
|
||
from dotenv import load_dotenv | ||
from asgiref.sync import sync_to_async | ||
|
||
load_dotenv() | ||
openai.api_key = os.getenv("OPENAI_API_KEY") | ||
|
||
async def draw(prompt) -> list[str]: | ||
|
||
# generate 512x512 image and save to a file | ||
# return the path of the image as a str | ||
async def draw(prompt, amount) -> list[str]: | ||
DATA_DIR = Path.cwd() | ||
DATA_DIR.mkdir(exist_ok=True) | ||
|
||
response = await sync_to_async(openai.Image.create)( | ||
response = await sync_to_async(openai.images.generate)( | ||
model="dall-e-3", | ||
prompt=prompt, | ||
n=amount, | ||
n=1, | ||
size="1024x1024", | ||
response_format="b64_json", | ||
quality="standard", | ||
) | ||
with open("response.log", mode="w", encoding="utf-8") as file: | ||
json.dump(response, file) | ||
|
||
file_name = DATA_DIR / f"{prompt[:5]}-{response['created']}.json" | ||
|
||
with open(file_name, mode="w", encoding="utf-8") as file: | ||
json.dump(response, file) | ||
|
||
path = await convert(file_name) | ||
path = [str(p) for p in path] | ||
return path | ||
|
||
# code stolen from https://realpython.com/generate-images-with-dalle-openai-api/ | ||
async def convert(path): | ||
DATA_DIR = Path.cwd() / "responses" | ||
JSON_FILE = DATA_DIR / path | ||
IMAGE_DIR = Path.cwd() / "images" | ||
IMAGE_DIR.mkdir(parents=True, exist_ok=True) | ||
|
||
with open(JSON_FILE, mode="r", encoding="utf-8") as file: | ||
response = json.load(file) | ||
image_files = [] | ||
for index, image_dict in enumerate(response["data"]): | ||
image_data = b64decode(image_dict["b64_json"]) | ||
image_file = IMAGE_DIR / f"{JSON_FILE.stem}-{index}.png" | ||
image_files.append(image_file) | ||
|
||
with open(image_file, mode="wb") as png: | ||
png.write(image_data) | ||
|
||
# delete uneeded json file | ||
os.remove(path) | ||
image_url = response.data[0].url | ||
|
||
return image_files | ||
return image_url |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters