Changed get_images(ws, prompt) to asynchronous method to prevent lost packets

This commit is contained in:
zeus 2024-05-03 16:09:15 -05:00
parent daa92a8ff4
commit 6a4cf05539

View File

@ -6,6 +6,7 @@ import uuid
import json import json
import urllib.request import urllib.request
import urllib.parse import urllib.parse
import asyncio
server_address = "127.0.0.1:8188" server_address = "127.0.0.1:8188"
client_id = str(uuid.uuid4()) client_id = str(uuid.uuid4())
@ -26,17 +27,23 @@ def get_history(prompt_id):
with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response: with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
return json.loads(response.read()) return json.loads(response.read())
def get_images(ws, prompt): async def receive(ws):
return ws.recv()
async def get_images(ws, prompt):
prompt_id = queue_prompt(prompt)['prompt_id'] prompt_id = queue_prompt(prompt)['prompt_id']
output_images = {} output_images = {}
while True: while True:
out = ws.recv() out = await receive(ws)
if isinstance(out, str): if isinstance(out, str):
message = json.loads(out) message = json.loads(out)
if message['type'] == 'executing': if message['type'] == 'executing':
data = message['data'] data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id: if data['node'] is None and data['prompt_id'] == prompt_id:
break #Execution is done break #Execution is done
elif message['type'] == 'progress':
data = message['data']
print("Processed step " + str(data['value']) + " out of " + str(data['max']))
else: else:
continue #previews are binary data continue #previews are binary data
@ -141,24 +148,26 @@ prompt_text = """
} }
} }
""" """
async def api_example():
prompt = json.loads(prompt_text)
#set the text prompt for our positive CLIPTextEncode
prompt["6"]["inputs"]["text"] = "masterpiece best quality man"
#set the seed for our KSampler node
prompt["3"]["inputs"]["seed"] = 5
ws = websocket.WebSocket()
ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
images = await get_images(ws, prompt)
prompt = json.loads(prompt_text) #Commented out code to display the output images:
#set the text prompt for our positive CLIPTextEncode
prompt["6"]["inputs"]["text"] = "masterpiece best quality man"
#set the seed for our KSampler node # for node_id in images:
prompt["3"]["inputs"]["seed"] = 5 # for image_data in images[node_id]:
# from PIL import Image
ws = websocket.WebSocket() # import io
ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id)) # image = Image.open(io.BytesIO(image_data))
images = get_images(ws, prompt) # image.show()
#Commented out code to display the output images:
# for node_id in images:
# for image_data in images[node_id]:
# from PIL import Image
# import io
# image = Image.open(io.BytesIO(image_data))
# image.show()
loop=asyncio.get_event_loop()
loop.run_until_complete(api_example())