ComfyUI icon indicating copy to clipboard operation
ComfyUI copied to clipboard

Is there an API you can call?

Open jdc4429 opened this issue 1 year ago • 31 comments

I just wanted to know if there was an API I can call like automatic? if so is it compatible, if not, are you going to add one? I run a website and currently use an API to allow users to create their own images. I was really liking that your interface can run SDXL (especially on my 8GB RTX 2070) and was hoping to implement it's API. 1080p images that can be used as wallpapers and such. Can also create an image in 4 different sizes currently. My website is https://AiImageCentral.com if anyone wants to check it out.

Regards,

Jeff

jdc4429 avatar Jul 21 '23 03:07 jdc4429

same needs

HuangZiy avatar Jul 22 '23 16:07 HuangZiy

Yes, read the top of: https://github.com/comfyanonymous/ComfyUI/blob/master/script_examples/basic_api_example.py

And this is how you can use the websockets: https://github.com/comfyanonymous/ComfyUI/blob/master/script_examples/websockets_api_example.py

comfyanonymous avatar Jul 22 '23 16:07 comfyanonymous

Thank you! Love your efficient use of memory and quick response.

Wow there are a lot of fields. I'm not sure what all of them do.

jdc4429 avatar Jul 22 '23 17:07 jdc4429

Seems to be an issue.. For some reason when I run the script it works the first time, but when you call it again after that it does not run.

got prompt 100%|████████████████████████████████████████████████████████████████| 20/20 [00:02<00:00, 8.41it/s] Prompt executed in 3.84 seconds got prompt Prompt executed in 0.00 seconds got prompt Prompt executed in 0.00 seconds

jdc4429 avatar Jul 22 '23 17:07 jdc4429

comfyui caches the node outputs of the last workflow so you submit the same workflow twice it won't execute anything in it.

Set a random seed instead of the fixed seed in the script.

comfyanonymous avatar Jul 22 '23 17:07 comfyanonymous

Hmm.. I did set to -1 for the seed.. Does it not recognize -1 as random? Nevermind, error says no values less then 1. :) I didn't notice at first the other fields changing the information at the bottom. Thank you!

jdc4429 avatar Jul 22 '23 17:07 jdc4429

Now my only issue in a random number generator.. I'm not finding what the actual range is for the seed for SD... Any idea what the max is? Does it depend on the model?

jdc4429 avatar Jul 22 '23 17:07 jdc4429

The max is: 18446744073709551616

comfyanonymous avatar Jul 22 '23 17:07 comfyanonymous

Well I thought it was working.. I have it working if I run the python script myself from the command line But when I try executing from shell I get this error...

Traceback (most recent call last): File "/var/www/html/comfy.py", line 181, in ws = websocket.WebSocket() TypeError: WebSocket.init() missing 3 required positional arguments: 'environ', 'socket', and 'rfile'

I'm not sure why... I install the websocket-client.. even put in script to install in environment. Says requirements are satisfied. Not sure if conflicting with another library. Will try creating environment for Comfy by itself.

jdc4429 avatar Jul 22 '23 18:07 jdc4429

For the websocket example: pip install websocket-client and make sure you don't have another package named "websocket" installed.

comfyanonymous avatar Jul 22 '23 18:07 comfyanonymous

I create a conda environment called comfy... which should be clean. Installed requirements.txt to comfy environment pip3 install websocket-client From my understanding, any outside package should not interfere? I'm not sure why I'm still getting the error... Traceback (most recent call last): File "/var/www/html/comfy.py", line 181, in ws = websocket.WebSocket() TypeError: WebSocket.init() missing 3 required positional arguments: 'environ', 'socket', and 'rfile'

I did pip list...

Package Version


bidict 0.22.1 click 8.1.3 Flask 2.2.5 Flask-SocketIO 5.3.4 importlib-metadata 6.6.0 itsdangerous 2.1.2 Jinja2 3.1.2 MarkupSafe 2.1.2 pip 23.2.1 python-engineio 4.4.1 python-socketio 5.8.0 setuptools 40.8.0 typing_extensions 4.5.0 websocket-client 1.6.1 Werkzeug 2.2.3 zipp 3.15.0

jdc4429 avatar Jul 22 '23 18:07 jdc4429

I even removed all websocket packages from base...

I still get the same error. I don't understand why. It was working previously and now It's not even working when I do it manually. This is really odd...

I rebooted my system... And now again I can do it manually. but when I try and execute from the python script I get the error above.

jdc4429 avatar Jul 22 '23 18:07 jdc4429

I even tried using my other webui interface.. but that doesn't work either. lol

RuntimeError: (405, '405: Method Not Allowed')

I would really like to get this working but I'm at a loss. I don't know what else I can try. I removed all other sockets, reinstalled a few times. Rebooted.. It keeps asking for those arguments when I execute from another python script...

jdc4429 avatar Jul 22 '23 18:07 jdc4429

What is really screwed up.. is I can run manually from base.. But when I go into the newly created comfy environment it gives me that error.

jdc4429 avatar Jul 22 '23 19:07 jdc4429

WebSocket.init() missing 3 required positional arguments: 'environ', 'socket', and 'rfile'

That means you have "websocket" installed not "websocket-client"

comfyanonymous avatar Jul 22 '23 19:07 comfyanonymous

I uninstalled it... and rebooted.. and that was only on base.. that should not affect the newly created conda environment. I think maybe my Conda environment is messed up somehow. I may try reinstalling Anaconda... No I specifically installed websocket-client and made sure to remove any other sockets even from base... Something is screwy.

jdc4429 avatar Jul 22 '23 19:07 jdc4429

I had an error with conda that was causing it to fail to allow me to install anything. I had to delete my whole anaconda3 dir and reinstall from scratch. Will setup everything I need from base and see what happens. Thanks again for your help.

jdc4429 avatar Jul 22 '23 19:07 jdc4429

I think something is screwy with that code..

Just reinstalled Anaconda completely. Installed all the requirements to base. Created a new conda environment for Comfy...

Look at this.. when run first time...

(comfy) jeff@jeff-desktop:/var/www/html$ python comfy.py "test" "test" 1920 1080 Defaulting to user installation because normal site-packages is not writeable Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com Collecting websocket-client Obtaining dependency information for websocket-client from https://files.pythonhosted.org/packages/d3/a3/63e9329c8cc9be6153e919e17d0ef5b60d537fed78564872951b95bcc17c/websocket_client-1.6.1-py3-none-any.whl.metadata Downloading websocket_client-1.6.1-py3-none-any.whl.metadata (7.6 kB) Downloading websocket_client-1.6.1-py3-none-any.whl (56 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 56.9/56.9 kB 326.6 kB/s eta 0:00:00 Installing collected packages: websocket-client Successfully installed websocket-client-1.6.1 Traceback (most recent call last): File "/var/www/html/comfy.py", line 181, in ws = websocket.WebSocket() TypeError: WebSocket.init() missing 3 required positional arguments: 'environ', 'socket', and 'rfile' (comfy) jeff@jeff-desktop:/var/www/html$

jdc4429 avatar Jul 22 '23 19:07 jdc4429

This is everything from the w's install from pip on my base...

w3lib 1.21.0 watchdog 2.1.6 wcwidth 0.2.5 webencodings 0.5.1 websocket-client 0.58.0 Werkzeug 2.2.3 whatthepatch 1.0.2 wheel 0.38.4 widgetsnbextension 4.0.5 wrapt 1.14.1 wurlitzer 3.0.2

No other sockets... Maybe it's the version?

Again.. I can run manually from base.. Just when I try to execute from script from running script or in the conda environment comfy.

Also...

(comfy) jeff@jeff-desktop:/var/www/html$ pip3 uninstall websockets WARNING: Skipping websockets as it is not installed. (comfy) jeff@jeff-desktop:/var/www/html$ pip3 uninstall websocket WARNING: Skipping websocket as it is not installed. (comfy) jeff@jeff-desktop:/var/www/html$ (base) jeff@jeff-desktop:~$ pip3 uninstall websockets WARNING: Skipping websockets as it is not installed. (base) jeff@jeff-desktop:~$ pip3 uninstall websocket WARNING: Skipping websocket as it is not installed. (base) jeff@jeff-desktop:~$

jdc4429 avatar Jul 22 '23 19:07 jdc4429

If you are still having issues with the API, I created an extension to convert any comfyui workflow (including custom nodes) into executable python code that will run without relying on the comfyui server. You just run the workflow_api.json file through the extension and it creates a python script that will immediate run your workflow.

If you are comfortable in Python, it may be more straightforward to use than the API. If interested, check it out here: https://github.com/pydn/ComfyUI-to-Python-Extension

pydn avatar Aug 20 '23 20:08 pydn

If you are still having issues with the API, I created an extension to convert any comfyui workflow (including custom nodes) into executable python code that will run without relying on the comfyui server. You just run the workflow_api.json file through the extension and it creates a python script that will immediate run your workflow.

If you are comfortable in Python, it may be more straightforward to use than the API. If interested, check it out here: https://github.com/pydn/ComfyUI-to-Python-Extension

It's amazing to add natively in ComfyUI (below Save API Format Button)

rossaai avatar Aug 23 '23 14:08 rossaai

Is it possible to call the endpoint and get the image back without using websockets? I'm attempting to call my ComfyUI server from AWS lambda. I had trouble getting it to allow websockets so I am using the regular API and I can get it queue up a message but it doesn't return the image or any indication of when its done. I want to avoid polling the server constantly until the generation is complete. I also have the same issue calling from Postman. any help would be appreciated

Thrasosoft avatar Aug 24 '23 16:08 Thrasosoft

@Thrasosoft I could be wrong, but I don't think you can use the API without polling the server. You could use my extension to automatically generate Python code from your workflow, which will execute your workflow without polling the server. https://github.com/pydn/ComfyUI-to-Python-Extension

pydn avatar Aug 24 '23 16:08 pydn

What would it take to get something like Automatic1111's "--no-gradio-queue" option that uses http requests instead of a websocket?

Thrasosoft avatar Aug 24 '23 17:08 Thrasosoft

What we opted for was to directly access the ComfyUI nodes using python and then build a simple API with FastAPI.

What would it take to get something like Automatic1111's "--no-gradio-queue" option that uses http requests instead of a websocket?

rossaai avatar Aug 25 '23 14:08 rossaai

When attempting to call the Server's /view? endpoint I am unable to figure out how to encode the image properly for display in a web-browser. It seems from the included script examples the data is being returned as bytes but I need it to be base64. However the below code does not get the job done. any reccomendations for correctly encoding the image information?

        const imageUrl = `${process.env.COMFY_UI_URL}/view?filename=${filename}`;
        try {
          const imageData = await requestHandler.get(imageUrl, requestOptions);
          if (imageData) {
            const base64Image = Buffer.from(imageData.data, "binary").toString("base64");
            response = { images: [base64Image] };
          } else {
            response = "Error Generating Images";
          }
        } catch (er) {
          console.log('Error getting image data: ',er);
          error = true;
          response = "Error Generating Images";
        }
      }
      return response;

The end result of this code is an encoded string that cannot be decoded as an image on the front-end. how have others solved this?

Thrasosoft avatar Aug 28 '23 21:08 Thrasosoft

When attempting to call the Server's /view? endpoint I am unable to figure out how to encode the image properly for display in a web-browser. It seems from the included script examples the data is being returned as bytes but I need it to be base64. However the below code does not get the job done. any reccomendations for correctly encoding the image information?

        const imageUrl = `${process.env.COMFY_UI_URL}/view?filename=${filename}`;
        try {
          const imageData = await requestHandler.get(imageUrl, requestOptions);
          if (imageData) {
            const base64Image = Buffer.from(imageData.data, "binary").toString("base64");
            response = { images: [base64Image] };
          } else {
            response = "Error Generating Images";
          }
        } catch (er) {
          console.log('Error getting image data: ',er);
          error = true;
          response = "Error Generating Images";
        }
      }
      return response;

The end result of this code is an encoded string that cannot be decoded as an image on the front-end. how have others solved this?

have you resolve this? base64 encode the out binary, can not preview, do you know why? @Thrasosoft

Richard0403 avatar Jan 11 '24 09:01 Richard0403

When attempting to call the Server's /view? endpoint I am unable to figure out how to encode the image properly for display in a web-browser. It seems from the included script examples the data is being returned as bytes but I need it to be base64. However the below code does not get the job done. any reccomendations for correctly encoding the image information?

        const imageUrl = `${process.env.COMFY_UI_URL}/view?filename=${filename}`;
        try {
          const imageData = await requestHandler.get(imageUrl, requestOptions);
          if (imageData) {
            const base64Image = Buffer.from(imageData.data, "binary").toString("base64");
            response = { images: [base64Image] };
          } else {
            response = "Error Generating Images";
          }
        } catch (er) {
          console.log('Error getting image data: ',er);
          error = true;
          response = "Error Generating Images";
        }
      }
      return response;

The end result of this code is an encoded string that cannot be decoded as an image on the front-end. how have others solved this?

have you resolve this? base64 encode the out binary, can not preview, do you know why? @Thrasosoft

yeah I solved this already. I needed to get the response as an array buffer and encode it as base64

export async function getBase64Image(url:string) {
  return requestHandler
    .get(url, {
      responseType: "arraybuffer",
    })
    .then((response) =>
      Buffer.from(response.data, "binary").toString("base64")
    );
}

Then in my img tag on my webapp I needed to specify the encoding in the img src

export const getImgSrc = (imageBytes) => {
  return "data:image/png;base64," + imageBytes;
};
...
          <img
            src={props.imgSrc ? props.imgSrc : getImgSrc(props.imgResult)}
            alt={props.character.portraitPrompt}
            className={section1Styles.image}
          />

ZachariBarnes avatar Jan 12 '24 20:01 ZachariBarnes

Hi, which ws endpoint/api I should use to get the current quenu size, including pending and running Thanks in advance

HamiguaLu avatar Mar 18 '24 02:03 HamiguaLu

Hi, which ws endpoint/api I should use to get the current quenu size, including pending and running Thanks in advance

Hi, @HamiguaLu , I think it's this: https://github.com/comfyanonymous/ComfyUI/blob/831511a1eecbe271e302f2f2053f285f00614180/server.py#L440

liusida avatar Apr 11 '24 01:04 liusida