Reputation: 11
I have a Comfy Ui server running on a server, I wanted to use the api with web socket from my computer, but although there is no problem when the web socket is running on the local host, I get errors when I try with the server address. I used ngrok and cloudflared to redirect the server address, but neither of them worked. I need help
#This is an example that uses the websockets api to know when a prompt execution is done
#Once the prompt execution is done it downloads the images using the /history endpoint
import websocket #NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
import uuid
import json
import urllib.request
import urllib.parse
import requests
server_address = "badf-95-7-52-49.ngrok-free.app"
client_id = str(uuid.uuid4())
def queue_prompt(prompt):
p = {"prompt": prompt, "client_id": client_id}
data = json.dumps(p).encode('utf-8')
req = urllib.request.Request("http://{}/prompt".format(server_address), data=data)
return json.loads(urllib.request.urlopen(req).read())
def get_image(filename, subfolder, folder_type):
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 set_image
def get_history(prompt_id):
with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
return json.loads(response.read())
def get_images(ws, prompt):
prompt_id = queue_prompt(prompt)['prompt_id']
output_images = {}
while True:
out = ws.recv()
if isinstance(out, str):
message = json.loads(out)
if message['type'] == 'executing':
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break #Execution is done
else:
continue #previews are binary data
history = get_history(prompt_id)[prompt_id]
for o in history['outputs']:
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
if 'images' in node_output:
images_output = []
for image in node_output['images']:
image_data = get_image(image['filename'], image['subfolder'], image['type'])
images_output.append(image_data)
output_images[node_id] = images_output
return output_images
def upload_file(file, subfolder="", overwrite=False):
try:
# Wrap file in formdata so it includes filename
body = {"image": file}
data = {}
if overwrite:
data["overwrite"] = "true"
if subfolder:
data["subfolder"] = subfolder
resp = requests.post(f"http://{server_address}/upload/image", files=body,data=data)
if resp.status_code == 200:
data = resp.json()
# Add the file to the dropdown list and update the widget value
path = data["name"]
if "subfolder" in data:
if data["subfolder"] != "":
path = data["subfolder"] + "/" + path
else:
print(f"{resp.status_code} - {resp.reason}")
except Exception as error:
print(error)
return path
#load workflow from file
with open("workflow3.json", "r", encoding="utf-8") as f:
workflow_data = f.read()
workflow = json.loads(workflow_data)
#set the text prompt for our positive CLIPTextEncode
#random seed
import random
seed = random.randint(1, 1000000000)
#set the image url
workflow["7"]["inputs"]["url"] = "https://i.hizliresim.com/6fy279d.jpg"
workflow["8"]["inputs"]["url"] = "https://media.licdn.com/dms/image/D4D03AQGev1Jwi8TzCQ/profile-displayphoto-shrink_800_800/0/1713355416560?e=2147483647&v=beta&t=iiz8OYnb-lKz2pmpT0STkvTR3yShXWscYAW-6nJ1nXU"
ws = websocket.WebSocket()
ws.connect("wss://requirements-mississippi-event-meeting.trycloudflare.com/".format(server_address, client_id))
images = get_images(ws, workflow)
#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()
# save image
image.save(f"{node_id}-{seed}.png")
error:
Traceback (most recent call last):
File "c:\Users\musta\OneDrive\Masaüstü\API\dreaminAI_websockets_api_example.py", line 126, in <module>
ws.connect("wss://requirements-mississippi-event-meeting.trycloudflare.com/".format(server_address, client_id))
File "C:\Users\musta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\websocket\_core.py", line 261, in connect
self.handshake_response = handshake(self.sock, url, *addrs, **options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\musta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\websocket\_handshake.py", line 65, in handshake
status, resp = _get_resp_headers(sock)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\musta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\websocket\_handshake.py", line 150, in _get_resp_headers
raise WebSocketBadStatusException(
websocket._exceptions.WebSocketBadStatusException: Handshake status 200 OK -+-+- {'date': 'Tue, 07 May 2024 19:33:36 GMT', 'content-type': 'text/html', 'transfer-encoding': 'chunked', 'connection': 'keep-alive', 'cf-ray': '8803a4855b60b3a7-MUC', 'cf-cache-status': 'DYNAMIC', 'accept-ranges': 'bytes', 'access-control-allow-origin': '*', 'last-modified': 'Sun, 14 Apr 2024 16:12:18 GMT', 'access-control-allow-credentials': 'true', 'access-control-allow-headers': 'Content-Type, Authorization', 'access-control-allow-methods': 'POST, GET, DELETE, PUT, OPTIONS', 'server': 'cloudflare'} -+-+- None
Upvotes: 1
Views: 803