This repository has been archived by the owner on Aug 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdalle2.py
162 lines (155 loc) · 5.44 KB
/
dalle2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import openai
import os
from dotenv import load_dotenv
import base64
from pathlib import Path
load_dotenv()
openai.api_key = os.getenv("openai_token")
def generate_and_download(prompt, id=None):
try:
prompt = prompt.replace(".", " ")
prompt = prompt.replace(",", " ")
prompt = prompt.replace("'", " ")
prompt = prompt.replace("!", " ")
prompt = prompt.replace("?", " ")
prompt = prompt.replace("&", " ")
prompt = prompt.replace(":", " ")
prompt = prompt.replace("-", " ")
prompt = prompt.replace("#", " ")
prompt = prompt.replace("*", " ")
prompt = prompt.replace("+", " ")
response = openai.Image.create(
prompt=prompt,
n=4,
size="1024x1024",
response_format='b64_json'
)
files = []
dir = os.getcwd()
count = 0
for generations in response['data']:
decoded = base64.decodebytes(response['data'][count]['b64_json'].encode("ascii"))
name = prompt.replace(" ", "")
if id is None:
fh = open(name + "_" + str(count) + ".png", "wb")
path = Path(dir, name + "_" + str(count)).with_suffix('.png')
else:
fh = open(name + "_" + str(count) + "_" + id + ".png", "wb")
path = Path(dir, name + "_" + str(count) + "_" + id).with_suffix('.png')
fh.write(decoded)
fh.close()
files.append(str(path))
count += 1
return files
except openai.error.InvalidRequestError:
print("dalle2 violation")
return "violation"
except:
print("dalle2 error")
return "failure"
# old dalle2 api module before the official API was available:
# #forked from ezzcodeezzlife/dalle2-in-python (https://github.com/ezzcodeezzlife/dalle2-in-python)
#
# import json
# import os
# import requests
# import time
# import urllib
# import urllib.request
#
# from pathlib import Path
#
# class Dalle2():
# def __init__(self, bearer):
# self.bearer = bearer
# self.batch_size = 4
# self.inpainting_batch_size = 3
# self.task_sleep_seconds = 3
#
# def generate(self, prompt):
# body = {
# "task_type": "text2im",
# "prompt": {
# "caption": prompt,
# "batch_size": self.batch_size,
# }
# }
#
# return self.get_task_response(body)
#
# def generate_and_download(self, prompt, image_dir=os.getcwd()):
# generations = self.generate(prompt)
# if not generations:
# return None
# elif generations == "failure":
# print("Failure!")
# return "failure"
# elif generations == "violation":
# print("Violation!")
# return "violation"
# else:
# return self.download(generations, image_dir)
#
# def get_task_response(self, body):
# url = "https://labs.openai.com/api/labs/tasks"
# headers = {
# 'Authorization': "Bearer " + self.bearer,
# 'Content-Type': "application/json",
# }
# count = 0
# for request in range(3):
# response = requests.post(url, headers=headers, data=json.dumps(body))
# if response.status_code != 200:
# count += 1
# if count == 3:
# print(response.text)
# return "failure"
# else:
# time.sleep(10)
# elif response.status_code == 200:
# break
#
# data = response.json()
# print(f"✔️ Task created with ID: {data['id']}")
# print("⌛ Waiting for task to finish...")
#
# while True:
# count = 0
# url = f"https://labs.openai.com/api/labs/tasks/{data['id']}"
# for get_response in range(3):
# try:
# response = requests.get(url, headers=headers)
# data = response.json()
# break
# except:
# count += 1
# if count == 3:
# return "failure"
# time.sleep(10)
# if not response.ok:
# print(f"Request failed with status: {response.status_code}, data: {response.json()}")
# return "failure"
# if data["status"] == "failed":
# print(f"Task failed: {data['status_information']}")
# return "failure"
# if data["status"] == "rejected":
# print(f"Task rejected: {data['status_information']}")
# return "violation"
# if data["status"] == "succeeded":
# print("🙌 Task completed!")
# return data["generations"]["data"]
# time.sleep(self.task_sleep_seconds)
#
# def download(self, generations, image_dir=os.getcwd()):
# if not generations:
# raise ValueError("generations is empty!")
#
# file_paths = []
# for generation in generations:
# image_url = generation["generation"]["image_path"]
# file_path = Path(image_dir, generation['id']).with_suffix('.png')
# file_paths.append(str(file_path))
# urllib.request.urlretrieve(image_url, file_path)
# print(f"✔️ Downloaded: {file_path}")
#
# return file_paths