Skip to content

Commit

Permalink
Enable checkbox (#124)
Browse files Browse the repository at this point in the history
* fix invert

* fix color switch

* double check is redundant

* better interface

* swap things

* refact

* details

* properly update ui when sending from png info

* move accordion ui to own module

* refact

* rename

* rename

* pass tab

* pass tab

* external_code, not global_state

* more reliable wait_until_donne

* fix server restart

* default value is all falses

* do not request default workflow for disabled workflow types

* comments

* return list of n batches

* oopie

* list

* fix date.now

* rename

* fix style and rename

* update docs

* check size
  • Loading branch information
ljleb authored Aug 13, 2023
1 parent 3741422 commit 0f92ca3
Show file tree
Hide file tree
Showing 12 changed files with 400 additions and 201 deletions.
4 changes: 2 additions & 2 deletions comfyui_custom_nodes/webui_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def INPUT_TYPES(cls):
OUTPUT_NODE = True

def set_images(self, images):
global_state.node_outputs += images.permute(0, 3, 1, 2)
global_state.node_outputs += [images.permute(0, 3, 1, 2)]
return []


Expand Down Expand Up @@ -78,7 +78,7 @@ def INPUT_TYPES(cls):

def set_images(self, latents):
latent_format = get_comfy_model_config().latent_format
global_state.node_outputs += latent_format.process_in(latents['samples'].to('cpu'))
global_state.node_outputs += [latent_format.process_in(latents['samples'].to('cpu'))]
return []


Expand Down
2 changes: 1 addition & 1 deletion comfyui_custom_scripts/extensions/webuiNodes.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function createVoidWidget(node, name) {
type: "customtext",
name,
get value() {
return `${Math.random()}{Date.now()}`;
return `${Math.random()}${Date.now()}`;
},
set value(x) {},
};
Expand Down
42 changes: 22 additions & 20 deletions javascript/compute-height.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,22 @@ const WEBUI_CLIENT_KEY = uuidv4();

function changeDisplayedWorkflowType(targetWorkflowType) {
const targetIFrameElement = getWorkflowTypeIFrame(targetWorkflowType);
const currentIFrameElement = targetIFrameElement.parentElement.querySelector(".comfyui-embedded-widget-display");
currentIFrameElement.classList.remove("comfyui-embedded-widget-display");
targetIFrameElement.classList.add("comfyui-embedded-widget-display");
const currentIFrameElement = targetIFrameElement.parentElement.querySelector(".comfyui-workflow-type-visible");
currentIFrameElement.classList.remove("comfyui-workflow-type-visible");
targetIFrameElement.classList.add("comfyui-workflow-type-visible");
}

document.addEventListener("DOMContentLoaded", () => {
onComfyuiTabLoaded(clearEnabledDisplayNames);
onComfyuiTabLoaded(setupComfyuiTabEvents);
});

function onComfyuiTabLoaded(callback) {
const workflowTypeIds = getWorkflowTypeIds();
const container = getComfyuiContainer();
const tabNav = getTabNav();

if (workflowTypeIds === null || container === null || tabNav === null) {
if (getClearEnabledDisplayNamesButtons().some(e => e === null) ||
getWorkflowTypeIds() === null ||
getComfyuiContainer() === null ||
getTabNav() === null
) {
// webui not yet ready, try again in a bit
setTimeout(() => { onComfyuiTabLoaded(callback); }, POLLING_TIMEOUT);
return;
Expand All @@ -31,8 +32,13 @@ function onComfyuiTabLoaded(callback) {
callback();
}

function clearEnabledDisplayNames() {
for (const clearButton of getClearEnabledDisplayNamesButtons()) {
clearButton.click();
}
}

function setupComfyuiTabEvents() {
setupReloadOnErrorEvent();
setupResizeTabEvent();
setupToggleFooterEvent();

Expand All @@ -41,17 +47,6 @@ function setupComfyuiTabEvents() {
getWorkflowTypeIds().forEach(id => forceFeedIdToIFrame(id));
}

function setupReloadOnErrorEvent() {
getWorkflowTypeIds().forEach(id => {
const comfyuiFrame = getWorkflowTypeIFrame(id);
comfyuiFrame.addEventListener("error", () => {
setTimeout(() => {
reloadFrameElement(comfyuiFrame);
}, POLLING_TIMEOUT);
});
});
}

function reloadComfyuiIFrames() {
getWorkflowTypeIds().forEach(id => {
const comfyuiFrame = getWorkflowTypeIFrame(id);
Expand Down Expand Up @@ -94,6 +89,13 @@ function updateFooterStyle() {
}
}

function getClearEnabledDisplayNamesButtons() {
return [
document.getElementById("script_txt2txt_comfyui_clear_enabled_display_names") ?? null,
document.getElementById("script_img2img_comfyui_clear_enabled_display_names") ?? null,
];
}

function getTabNav() {
const tabs = document.getElementById("tabs") ?? null;
return tabs ? tabs.querySelector(".tab-nav") : null;
Expand Down
17 changes: 11 additions & 6 deletions lib_comfyui/comfyui/iframe_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,17 @@ def send(request_params):
@staticmethod
@ipc.restrict_to_process('webui')
def start_workflow_sync(
batch_input: List[torch.Tensor],
batch_input: torch.Tensor,
workflow_type_id: str,
queue_front: bool,
):
) -> List[torch.Tensor]:
from modules import shared
if shared.state.interrupted:
return batch_input
return [batch_input]

if is_default_workflow(workflow_type_id):
print('[sd-webui-comfyui]', f'Skipping workflow {workflow_type_id} because it is empty.')
return batch_input
return [batch_input]

global_state.node_inputs = batch_input
global_state.node_outputs = []
Expand All @@ -64,10 +64,10 @@ def start_workflow_sync(
})
except RuntimeError as e:
print('\n'.join(traceback.format_exception_only(e)))
return batch_input
return [batch_input]

if not queue_tracker.wait_until_done():
return batch_input
return [batch_input]

return global_state.node_outputs

Expand Down Expand Up @@ -125,6 +125,8 @@ def is_default_workflow(workflow_type_id, current_graph=None):

current_graph['nodes'].sort(key=lambda e: e['type'])
default_graph['nodes'].sort(key=lambda e: e['type'])
if not all(current_graph['nodes'][i]['type'] == default_graph['nodes'][i]['type'] for i in range(nodes_len)):
return False

def create_adjacency_matrix(graph):
adjacency_matrix = torch.zeros((nodes_len,) * 2, dtype=torch.bool)
Expand All @@ -149,6 +151,9 @@ def extend_infotext_with_comfyui_workflows(p, tab):
workflows = {}
for workflow_type in external_code.get_workflow_types(tab):
workflow_type_id = workflow_type.get_ids(tab)[0]
if not getattr(global_state, 'enabled_workflow_type_ids', {}).get(workflow_type_id, False):
continue

graph = get_workflow_graph(workflow_type_id)
if is_default_workflow(workflow_type_id, graph):
continue
Expand Down
7 changes: 3 additions & 4 deletions lib_comfyui/comfyui/queue_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ def wait_until_done():
has_been_set = check_done_event(timeout=1)
if has_been_set:
return True
elif not tracked_id_present():
return False
elif shared.state.interrupted:
cancel_queued_workflow()
return False
Expand All @@ -100,9 +102,6 @@ def wait_until_put():
PromptQueueTracker.tracked_id = PromptQueueTracker.original_id
return False

if not tracked_id_present():
return False

return True


Expand All @@ -122,7 +121,7 @@ def cancel_queued_workflow():
PromptQueueTracker.queue_instance.delete_queue_item(lambda a: a[1] == PromptQueueTracker.tracked_id)


@ipc.restrict_to_process('comfyui')
@ipc.run_in_process('comfyui')
def tracked_id_present():
with PromptQueueTracker.queue_instance.mutex:
for v in PromptQueueTracker.queue_instance.currently_running.values():
Expand Down
18 changes: 12 additions & 6 deletions lib_comfyui/external_code/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def get_default_workflow_json(workflow_type_id: str) -> str:
def run_workflow(
workflow_type: WorkflowType,
tab: str,
batch_input: List[Any],
batch_input: Any,
queue_front: Optional[bool] = None,
) -> List[Any]:
"""
Expand All @@ -180,24 +180,30 @@ def run_workflow(
batch_input (List[ANy]): Batch objects to pass to the workflow. The number of elements in batch_input is the size of the comfyui batch
queue_front (Optional[bool]): Whether to queue the workflow before or after the currently queued workflows
Returns:
The output of the workflow. The size of the output does not necessarily match len(batch_input)
The outputs of the workflow
The size of the returned list corresponds to the number of output nodes in the workflow
Each element of the list will have the same batch size as batch_input
Raises:
ValueError: If workflow_type is not present on the given tab
AssertionError: If multiple candidate ids exist for workflow_type
"""
from lib_comfyui.comfyui.iframe_requests import ComfyuiIFrameRequests

if queue_front is None:
queue_front = getattr(global_state, 'queue_front', True)

candidate_ids = workflow_type.get_ids(tab)
assert len(candidate_ids) <= 1, f'Found multiple candidate workflow type ids for tab {tab} and workflow type {workflow_type.pretty_str()}: {candidate_ids}'

if not candidate_ids:
raise ValueError(f'Incompatible tab {tab} and workflow type {workflow_type.pretty_str()}. Valid tabs for the given workflow type: {workflow_type.tabs}')

workflow_type_id = candidate_ids[0]
if not (getattr(global_state, 'enable', True) and getattr(global_state, 'enabled_workflow_type_ids', {}).get(workflow_type_id, False)):
return [batch_input]

if queue_front is None:
queue_front = getattr(global_state, 'queue_front', True)

return ComfyuiIFrameRequests.start_workflow_sync(
batch_input=batch_input,
workflow_type_id=candidate_ids[0],
workflow_type_id=workflow_type_id,
queue_front=queue_front,
)
Loading

0 comments on commit 0f92ca3

Please sign in to comment.