-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuntitled.py
182 lines (146 loc) · 7.63 KB
/
untitled.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def open_websocket_connection():
server_address='127.0.0.1:8188'
client_id=str(uuid.uuid4())
ws = websocket.WebSocket()
ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
return ws, server_address, client_id
def queue_prompt(prompt, client_id, server_address):
p = {"prompt": prompt, "client_id": client_id}
headers = {'Content-Type': 'application/json'}
data = json.dumps(p).encode('utf-8')
req = urllib.request.Request("http://{}/prompt".format(server_address), data=data, headers=headers)
return json.loads(urllib.request.urlopen(req).read())
def get_history(prompt_id, server_address):
with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
return json.loads(response.read())
def get_image(filename, subfolder, folder_type, server_address):
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
with urllib.request.urlopen("http://{}/view?{}".format(server_address, url_values)) as response:
return response.read()
def upload_image(input_path, name, server_address, image_type="input", overwrite=False):
with open(input_path, 'rb') as file:
multipart_data = MultipartEncoder(
fields= {
'image': (name, file, 'image/png'),
'type': image_type,
'overwrite': str(overwrite).lower()
}
)
data = multipart_data
headers = { 'Content-Type': multipart_data.content_type }
request = urllib.request.Request("http://{}/upload/image".format(server_address), data=data, headers=headers)
with urllib.request.urlopen(request) as response:
return response.read()
def load_workflow(workflow_path):
try:
with open(workflow_path, 'r') as file:
workflow = json.load(file)
return json.dumps(workflow)
except FileNotFoundError:
print(f"The file {workflow_path} was not found.")
return None
except json.JSONDecodeError:
print(f"The file {workflow_path} contains invalid JSON.")
return None
def prompt_to_image(workflow, positve_prompt, negative_prompt='', save_previews=False):
prompt = json.loads(workflow)
id_to_class_type = {id: details['class_type'] for id, details in prompt.items()}
k_sampler = [key for key, value in id_to_class_type.items() if value == 'KSampler'][0]
prompt.get(k_sampler)['inputs']['seed'] = random.randint(10**14, 10**15 - 1)
postive_input_id = prompt.get(k_sampler)['inputs']['positive'][0]
prompt.get(postive_input_id)['inputs']['text'] = positve_prompt
if negative_prompt != '':
negative_input_id = prompt.get(k_sampler)['inputs']['negative'][0]
prompt.get(negative_input_id)['inputs']['text'] = negative_prompt
generate_image_by_prompt(prompt, './output/', save_previews)
def generate_image_by_prompt(prompt, output_path, save_previews=False):
try:
ws, server_address, client_id = open_websocket_connection()
prompt_id = queue_prompt(prompt, client_id, server_address)['prompt_id']
track_progress(prompt, ws, prompt_id)
images = get_images(prompt_id, server_address, save_previews)
save_image(images, output_path, save_previews)
finally:
ws.close()
def track_progress(prompt, ws, prompt_id):
node_ids = list(prompt.keys())
finished_nodes = []
while True:
out = ws.recv()
if isinstance(out, str):
message = json.loads(out)
if message['type'] == 'progress':
data = message['data']
current_step = data['value']
print('In K-Sampler -> Step: ', current_step, ' of: ', data['max'])
if message['type'] == 'execution_cached':
data = message['data']
for itm in data['nodes']:
if itm not in finished_nodes:
finished_nodes.append(itm)
print('Progess: ', len(finished_nodes), '/', len(node_ids), ' Tasks done')
if message['type'] == 'executing':
data = message['data']
if data['node'] not in finished_nodes:
finished_nodes.append(data['node'])
print('Progess: ', len(finished_nodes), '/', len(node_ids), ' Tasks done')
if data['node'] is None and data['prompt_id'] == prompt_id:
break #Execution is done
else:
continue
return
def get_images(prompt_id, server_address, allow_preview = False):
output_images = []
history = get_history(prompt_id, server_address)[prompt_id]
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
output_data = {}
if 'images' in node_output:
for image in node_output['images']:
if allow_preview and image['type'] == 'temp':
preview_data = get_image(image['filename'], image['subfolder'], image['type'], server_address)
output_data['image_data'] = preview_data
if image['type'] == 'output':
image_data = get_image(image['filename'], image['subfolder'], image['type'], server_address)
output_data['image_data'] = image_data
output_data['file_name'] = image['filename']
output_data['type'] = image['type']
output_images.append(output_data)
return output_images
def save_image(images, output_path, save_previews):
for itm in images:
directory = os.path.join(output_path, 'temp/') if itm['type'] == 'temp' and save_previews else output_path
os.makedirs(directory, exist_ok=True)
try:
image = Image.open(io.BytesIO(itm['image_data']))
image.save(os.path.join(directory, itm['file_name']))
except Exception as e:
print(f"Failed to save image {itm['file_name']}: {e}")
def prompt_image_to_image(workflow, input_path, positve_prompt, negative_prompt='', save_previews=False):
prompt = json.loads(workflow)
id_to_class_type = {id: details['class_type'] for id, details in prompt.items()}
k_sampler = [key for key, value in id_to_class_type.items() if value == 'KSampler'][0]
prompt.get(k_sampler)['inputs']['seed'] = random.randint(10**14, 10**15 - 1)
postive_input_id = prompt.get(k_sampler)['inputs']['positive'][0]
prompt.get(postive_input_id)['inputs']['text'] = positve_prompt
if negative_prompt != '':
negative_input_id = prompt.get(k_sampler)['inputs']['negative'][0]
prompt.get(negative_input_id)['inputs']['text'] = negative_prompt
image_loader = [key for key, value in id_to_class_type.items() if value == 'LoadImage'][0]
filename = input_path.split('/')[-1]
prompt.get(image_loader)['inputs']['image'] = filename
generate_image_by_prompt_and_image(prompt, './output/', input_path, filename, save_previews)
def generate_image_by_prompt_and_image(prompt, output_path, input_path, filename, save_previews=False):
try:
ws, server_address, client_id = open_websocket_connection()
upload_image(input_path, filename, server_address)
prompt_id = queue_prompt(prompt, client_id, server_address)['prompt_id']
track_progress(prompt, ws, prompt_id)
images = get_images(prompt_id, server_address, save_previews)
save_image(images, output_path, save_previews)
finally:
try:
ws.close()
if __name__ == "__main__":
generate_image_by_prompt_and_image("test prompt", "./", "src/image-refinement/", "canvas.png", save_previews=True)