sd_comfy_api.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import json
  2. from urllib import request, parse
  3. import random
  4. # This is the ComfyUI api prompt format.
  5. # If you want it for a specific workflow you can "enable dev mode options"
  6. # in the settings of the UI (gear beside the "Queue Size: ") this will enable
  7. # a button on the UI to save workflows in api format.
  8. # keep in mind ComfyUI is pre alpha software so this format will change a bit.
  9. # this is the one for the default workflow
  10. # load the prompt from a workflow_api_test.json file
  11. with open(
  12. "D://Temp//ComfyUI_windows_portable_nvidia//ComfyUI_windows_portable//ComfyUI//script_examples//custom//workflow_api_test.json",
  13. "r",
  14. ) as f:
  15. prompt_text_json = f.read()
  16. def queue_prompt(prompt):
  17. p = {"prompt": prompt}
  18. data = json.dumps(p).encode("utf-8")
  19. req = request.Request("http://127.0.0.1:8188/prompt", data=data)
  20. request.urlopen(req)
  21. def find_node(json_obj, title):
  22. for key, value in json_obj.items():
  23. if isinstance(value, dict):
  24. if value.get("_meta", {}).get("title") == title:
  25. return value
  26. else:
  27. result = find_node(value, title)
  28. if result:
  29. return result
  30. return None
  31. def set_filename(json_obj, title, new_prefix):
  32. for key, value in json_obj.items():
  33. if isinstance(value, dict):
  34. if value.get("_meta", {}).get("title") == title:
  35. if "inputs" in value and "filename_prefix" in value["inputs"]:
  36. value["inputs"]["filename_prefix"] = new_prefix
  37. else:
  38. result = set_filename(value, title, new_prefix)
  39. if result:
  40. return result
  41. return None
  42. prompt = json.loads(prompt_text_json)
  43. set_filename(prompt, "Save Image", "custom/basic_api_example")
  44. ksampler_main = find_node(prompt, "KSampler")
  45. ksampler_main["inputs"]["seed"] = random.randint(0, 1000000)
  46. prompt_positive = find_node(prompt, "prompt_positive")
  47. prompt_positive["inputs"][
  48. "text"
  49. ] = "cosmetics bottle at sunset, beautiful product advertising, luxury"
  50. prompt_negative = find_node(prompt, "prompt_negative")
  51. prompt_negative["inputs"]["text"] = "ugly, bad"
  52. queue_prompt(prompt)