Skip to content

Transform your 3D texturing workflow with the power of generative AI, directly within Blender!

report comfyui progress per server stage

sakalondcb0c80e65f91
diff --git a/stablegen/_generator_utils.py b/stablegen/_generator_utils.py
index 7808577..f02b251 100644
--- a/stablegen/_generator_utils.py
+++ b/stablegen/_generator_utils.py
@@ -14,6 +14,7 @@ import uuid
import requests
from .timeout_config import get_timeout
+from .generation_status import reporting_upload
def redraw_ui(context):
"""Redraws the UI to reflect changes in the operator's progress and status."""
@@ -81,7 +82,7 @@ def _pbr_setup_studio_lights(context, to_texture):
setup_studio_lighting(context, scale=max_dim)
-def upload_image_to_comfyui(server_address, image_path, image_type="input"):
+def upload_image_to_comfyui(server_address, image_path, image_type="input", *, operator=None):
"""
Uploads an image file to the ComfyUI server's /upload/image endpoint.
@@ -89,6 +90,7 @@ def upload_image_to_comfyui(server_address, image_path, image_type="input"):
server_address (str): The address:port of the ComfyUI server (e.g., "127.0.0.1:8188").
image_path (str): The local path to the image file to upload.
image_type (str): The type parameter for the upload (usually "input").
+ operator: Optional generation operator whose UI reports this transfer.
Returns:
dict: A dictionary containing the server's response (e.g., {'name': 'filename.png', 'subfolder': '', 'type': 'input'})
@@ -106,7 +108,7 @@ def upload_image_to_comfyui(server_address, image_path, image_type="input"):
print(f"[StableGen] Uploading {os.path.basename(image_path)} to {upload_url}...")
try:
- with open(image_path, 'rb') as f:
+ with reporting_upload(operator, image_path), open(image_path, 'rb') as f:
# Determine mime type based on extension
mime_type = 'application/octet-stream' # Default fallback
if image_path.lower().endswith('.png'):
diff --git a/stablegen/generation_status.py b/stablegen/generation_status.py
new file mode 100644
index 0000000..e5eed1c
--- /dev/null
+++ b/stablegen/generation_status.py
@@ -0,0 +1,112 @@
+"""Server status presentation without Blender or workflow dependencies."""
+
+from contextlib import contextmanager
+import os
+import time
+
+
+WAITING_STAGES = (
+ 'Uploading Images', 'Submitting Workflow', 'Queued on Server',
+ 'Preparing Inputs', 'Loading Models', 'Preparing Conditioning',
+ 'Starting Sampler', 'Decoding Image', 'Saving Result', 'Receiving Result',
+ 'Processing on Server',
+)
+
+
+def server_status_active(operator):
+ return bool(getattr(operator, '_server_stage', None)) and (
+ operator._server_stage == getattr(operator, '_stage', None)
+ )
+
+
+def set_server_stage(operator, stage, detail='', progress=None):
+ """Track elapsed time per node; percentages belong to that node only."""
+ if (not server_status_active(operator)
+ or operator._server_stage != stage
+ or getattr(operator, '_server_stage_detail', '') != detail):
+ operator._server_stage_started = time.monotonic()
+ operator._server_step_text = ''
+ operator._stage = stage
+ operator._server_stage = stage
+ operator._server_stage_detail = detail
+ operator._server_node_progress = progress
+ if hasattr(operator, '_detail_stage'):
+ operator._detail_stage = stage
+ if hasattr(operator, '_detail_progress'):
+ operator._detail_progress = progress or 0.0
+
+
+@contextmanager
+def reporting_upload(operator, image_path):
+ """Show upload status only around a real transfer, restoring caller state."""
+ if operator is None:
+ yield
+ return
+ missing = object()
+ names = ('_stage', '_server_stage', '_server_stage_started',
+ '_server_stage_detail', '_server_node_progress',
+ '_server_step_text',
+ '_detail_stage', '_detail_progress')
+ previous = {name: getattr(operator, name, missing) for name in names}
+ set_server_stage(operator, 'Uploading Images', os.path.basename(image_path))
+ try:
+ yield
+ finally:
+ for name, value in previous.items():
+ if value is missing:
+ if hasattr(operator, name):
+ delattr(operator, name)
+ else:
+ setattr(operator, name, value)
+
+
+def node_stage(node_id, node_info, node_map):
+ """Classify execution, excluding sampler selectors and model patchers."""
+ kind = node_info.get('class_type', '')
+ if (str(node_id) == str(node_map.get('sampler', ''))
+ or kind in {'KSampler', 'KSamplerAdvanced', 'SamplerCustom',
+ 'SamplerCustomAdvanced'}):
+ return 'Starting Sampler'
+ if kind == 'LoadImage':
+ return 'Preparing Inputs'
+ if 'Loader' in kind or kind.startswith('Load'):
+ return 'Loading Models'
+ if 'Decode' in kind:
+ return 'Decoding Image'
+ if 'Encode' in kind or 'Conditioning' in kind:
+ return 'Preparing Conditioning'
+ if kind.startswith('Save'):
+ return 'Saving Result'
+ return 'Processing on Server'
+
+
+def stage_progress(operator):
+ if server_status_active(operator):
+ return getattr(operator, '_server_node_progress', None) or 0.0
+ return getattr(operator, '_progress', 0.0)
+
+
+def stage_text(operator, default='Generating'):
+ stage = getattr(operator, '_stage', '') or default
+ if server_status_active(operator):
+ elapsed = max(0, int(time.monotonic() - operator._server_stage_started))
+ duration = f'{elapsed // 60}m {elapsed % 60:02d}s' if elapsed >= 60 else f'{elapsed}s'
+ label = 'Generating' if stage == 'Generating Image' else stage
+ steps = getattr(operator, '_server_step_text', '').removeprefix('Step ')
+ text = ' · '.join(part for part in (label, steps, duration) if part)
+ progress = getattr(operator, '_server_node_progress', None)
+ return f'{text} ({progress:.0f}%)' if progress is not None else text
+ return f"{stage} ({getattr(operator, '_progress', 0.0):.0f}%)"
+
+
+def draw_stage_progress(layout, operator, default='Generating'):
+ """Used by the native panel and its captured Studio presentation."""
+ bar = layout.progress(text=stage_text(operator, default),
+ factor=max(0.0, min(stage_progress(operator) / 100.0, 1.0)))
+ # Native UILayout.progress returns None. The Studio adapter returns its
+ # captured control so hover help stays metadata, outside Blender's API.
+ if bar is not None and server_status_active(operator):
+ context = (getattr(operator, '_server_context_stage', '')
+ if getattr(operator, '_pbr_active', False) else '')
+ detail = getattr(operator, '_server_stage_detail', '')
+ bar.tooltip = '\n'.join(part for part in (context, detail) if part)
diff --git a/stablegen/mesh_gen/workflows.py b/stablegen/mesh_gen/workflows.py
index a4db0a5..ed455bb 100644
--- a/stablegen/mesh_gen/workflows.py
+++ b/stablegen/mesh_gen/workflows.py
@@ -1211,7 +1211,7 @@ class _Trellis2WorkflowMixin:
rasterized_tmp = maybe_tmp
input_image_path = rasterized_tmp
- image_info = upload_image_to_comfyui(server_address, input_image_path)
+ image_info = upload_image_to_comfyui(server_address, input_image_path, operator=self.operator)
# Clean up the temp rasterized file after upload
if rasterized_tmp:
diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.py
index 791efb1..434c75d 100644
--- a/stablegen/texturing/generator.py
+++ b/stablegen/texturing/generator.py
@@ -1886,7 +1886,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
for unit in context.scene.controlnet_units:
unit.strength = 0.0
else:
- self._stage = "Uploading to Server"
+ self._stage = "Preparing Workflow"
self._progress = 0
# Generate the image
@@ -1965,7 +1965,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._run_on_main_thread(context_callback)
if self._error:
return
- self._stage = "Uploading to Server"
+ self._stage = "Preparing Workflow"
# Get info for the previous render and mask
render_info = self._get_uploaded_image_info(context, "inpaint", subtype="render", camera_id=self._current_image)
mask_info = self._get_uploaded_image_info(context, "inpaint", subtype="visibility", camera_id=self._current_image)
@@ -2936,7 +2936,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
# Not cached and file exists, try to upload it
server_address = context.preferences.addons[_ADDON_PKG].preferences.server_address
- uploaded_info = upload_image_to_comfyui(server_address, absolute_local_path)
+ uploaded_info = upload_image_to_comfyui(server_address, absolute_local_path, operator=self)
# Store result (the info dict or None if upload failed) in cache
self._uploaded_images_cache[absolute_local_path] = uploaded_info
diff --git a/stablegen/texturing/masked_edit.py b/stablegen/texturing/masked_edit.py
index 86d4c67..165ef14 100644
--- a/stablegen/texturing/masked_edit.py
+++ b/stablegen/texturing/masked_edit.py
@@ -873,7 +873,7 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
if depth:
paths['depth'] = depth
for key, path in paths.items():
- uploaded = upload_image_to_comfyui(server, str(path))
+ uploaded = upload_image_to_comfyui(server, str(path), operator=self)
if not uploaded:
raise RuntimeError(f'Could not upload {key}')
subfolder = uploaded.get('subfolder', '')
@@ -965,7 +965,7 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
args=(context, render, generation, overlay, depth, self.result),
daemon=True,
)
- self._stage = 'Uploading to Server'
+ self._stage = 'Preparing Workflow'
self._progress = 0
self.worker.start()
self.phase = 'generate'
diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.py
index 6aebe74..ad2db70 100644
--- a/stablegen/texturing/workflows.py
+++ b/stablegen/texturing/workflows.py
@@ -1786,7 +1786,7 @@ class _TexturingWorkflowMixin:
# Upload the source image to ComfyUI's input folder
from .._generator_utils import upload_image_to_comfyui
- image_info = upload_image_to_comfyui(server_address, input_image_path)
+ image_info = upload_image_to_comfyui(server_address, input_image_path, operator=self.operator)
if image_info is None:
return {"error": f"Failed to upload image for PBR decomposition: {input_image_path}"}
@@ -1943,7 +1943,7 @@ class _TexturingWorkflowMixin:
# Upload the source image to ComfyUI's input folder
from .._generator_utils import upload_image_to_comfyui
- image_info = upload_image_to_comfyui(server_address, input_image_path)
+ image_info = upload_image_to_comfyui(server_address, input_image_path, operator=self.operator)
if image_info is None:
return {"error": f"Failed to upload image for StableDelight: {input_image_path}"}
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 2b5dffc..d683490 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -3,6 +3,7 @@
import os
import bpy # pylint: disable=import-error
import mathutils # pylint: disable=import-error
+from ..generation_status import draw_stage_progress, server_status_active
import math
from ..utils import sg_modal_active
from ..core import get_addon_prefs
@@ -300,7 +301,9 @@ class StableGenPanel(bpy.types.Panel):
# Bar 3 — Detail (only when there's actual sampler progress)
detail_pct = getattr(trellis2_op, '_detail_progress', 0)
detail_label = getattr(trellis2_op, '_detail_stage', '')
- if detail_label and detail_pct > 0:
+ if server_status_active(trellis2_op):
+ draw_stage_progress(progress_col, trellis2_op)
+ elif detail_label and detail_pct > 0:
progress_col.progress(
text=f"{detail_label} ({detail_pct:.0f}%)",
factor=max(0.0, min(detail_pct / 100.0, 1.0))
@@ -371,7 +374,10 @@ class StableGenPanel(bpy.types.Panel):
factor=max(0.0, min(overall_pct / 100.0, 1.0))
)
# Bar 2 — Current model (camera progress)
- progress_col.progress(text=stage_text, factor=max(0.0, min(cam_frac, 1.0)))
+ if server_status_active(comfy_tex_op):
+ draw_stage_progress(progress_col, comfy_tex_op)
+ else:
+ progress_col.progress(text=stage_text, factor=max(0.0, min(cam_frac, 1.0)))
# Bar 3 — PBR step N/M
progress_col.progress(text=f"PBR: Step {pbr_step}/{pbr_total}", factor=pbr_frac)
else:
@@ -397,12 +403,7 @@ class StableGenPanel(bpy.types.Panel):
)
# Bar 2 — Per-image (same as normal ComfyUI bar)
- stage = getattr(comfy_tex_op, '_stage', 'Generating')
- img_pct = getattr(comfy_tex_op, '_progress', 0)
- progress_col.progress(
- text=f"{stage} ({img_pct:.0f}%)",
- factor=max(0.0, min(img_pct / 100.0, 1.0))
- )
+ draw_stage_progress(progress_col, comfy_tex_op)
# Bar 3 — Image N/M (same as normal ComfyUI overall bar)
if total_imgs > 1:
@@ -428,12 +429,14 @@ class StableGenPanel(bpy.types.Panel):
pbr_cam_total = max(getattr(comfy_tex_op, '_pbr_cam_total', 1), 1)
cam_frac = pbr_cam / pbr_cam_total
stage_text = getattr(comfy_tex_op, '_stage', 'PBR Decomposition')
- progress_col.progress(text=stage_text, factor=max(0.0, min(cam_frac, 1.0)))
+ if server_status_active(comfy_tex_op):
+ draw_stage_progress(progress_col, comfy_tex_op)
+ else:
+ progress_col.progress(text=stage_text, factor=max(0.0, min(cam_frac, 1.0)))
pbr_factor = max(0.0, min(((pbr_step - 1) + cam_frac) / pbr_total, 1.0))
progress_col.progress(text=f"PBR: Step {pbr_step}/{pbr_total}", factor=pbr_factor)
else:
- progress_text = f"{getattr(comfy_tex_op, '_stage', 'Generating')} ({getattr(comfy_tex_op, '_progress', 0):.0f}%)"
- progress_col.progress(text=progress_text, factor=max(0.0, min(raw_progress, 1.0)))
+ draw_stage_progress(progress_col, comfy_tex_op)
total_images = getattr(comfy_tex_op, '_total_images', 0)
if total_images > 1:
current_image_idx = getattr(comfy_tex_op, '_current_image', 0)
@@ -482,11 +485,7 @@ class StableGenPanel(bpy.types.Panel):
action_row.operator('stablegen.stop_masked_edit', text='Stop After Current View', icon='CANCEL')
progress_col = layout.column()
stage_pct = max(0.0, min(getattr(masked_op, '_progress', 0.0), 100.0))
- stage = getattr(masked_op, '_stage', 'Preparing Masked Edit')
- progress_col.progress(
- text=f'{stage} ({stage_pct:.0f}%)',
- factor=stage_pct / 100.0,
- )
+ draw_stage_progress(progress_col, masked_op, 'Preparing Masked Edit')
overall_pct = max(0.0, min(getattr(masked_op, '_overall_progress', 0.0), 100.0))
progress_col.progress(
text=getattr(masked_op, '_overall_label', 'Overall Masked Edit'),
@@ -555,10 +554,13 @@ class StableGenPanel(bpy.types.Panel):
# Top bar: camera X out of N within this step
cam_frac = pbr_cam / pbr_cam_total
stage_text = getattr(operator_instance, '_stage', 'PBR Decomposition')
- progress_col.progress(
- text=stage_text,
- factor=max(0.0, min(cam_frac, 1.0))
- )
+ if server_status_active(operator_instance):
+ draw_stage_progress(progress_col, operator_instance)
+ else:
+ progress_col.progress(
+ text=stage_text,
+ factor=max(0.0, min(cam_frac, 1.0))
+ )
# Bottom bar: overall PBR progress
pbr_factor = max(0.0, min(
((pbr_step - 1) + cam_frac) / pbr_total, 1.0))
@@ -568,8 +570,7 @@ class StableGenPanel(bpy.types.Panel):
)
else:
# Normal generation progress
- progress_text = f"{getattr(operator_instance, '_stage', 'Generating')} ({getattr(operator_instance, '_progress', 0):.0f}%)"
- progress_col.progress(text=progress_text, factor=max(0.0, min(raw_progress, 1.0)))
+ draw_stage_progress(progress_col, operator_instance)
total_images = getattr(operator_instance, '_total_images', 0)
if total_images > 1:
diff --git a/stablegen/ui/presentation.py b/stablegen/ui/presentation.py
index c0620d6..0524470 100644
--- a/stablegen/ui/presentation.py
+++ b/stablegen/ui/presentation.py
@@ -87,6 +87,7 @@ class Control:
args: tuple
kwargs: dict
properties: dict = field(default_factory=dict)
+ tooltip: str = ''
def render(self, layout, *, narrow=False):
if (narrow and self.method == 'prop' and self.args[1]
@@ -133,7 +134,9 @@ class Layout:
return child
child = Control(name, args, kwargs)
self.children.append(child)
- return OperatorProperties(child) if name == 'operator' else None
+ if name == 'operator':
+ return OperatorProperties(child)
+ return child if name == 'progress' else None
return record
def controls(self):
diff --git a/stablegen/workflows.py b/stablegen/workflows.py
index 31e4039..dc21a9e 100644
--- a/stablegen/workflows.py
+++ b/stablegen/workflows.py
@@ -12,6 +12,7 @@ from datetime import datetime, timezone, timedelta
from .timeout_config import get_timeout
from .prompt_archive import archive_prompt
+from .generation_status import set_server_stage, node_stage
from io import BytesIO
import numpy as np
@@ -390,7 +391,14 @@ class _WorkflowBase:
prompt, NODES.get('save_image', ''))
# Send the prompt to the queue
+ self.operator._server_context_stage = (
+ getattr(self.operator, '_stage', '')
+ if getattr(self.operator, '_pbr_active', False) else ''
+ )
+ self.operator._progress = 0.0
+ set_server_stage(self.operator, 'Submitting Workflow')
prompt_id = self._queue_prompt(prompt, client_id, server_address)
+ set_server_stage(self.operator, 'Queued on Server')
# Make every texturing workflow cancellable while blocked in recv().
# cancel_generate() closes this socket after interrupting ComfyUI.
@@ -425,6 +433,10 @@ class _WorkflowBase:
if state in {'running', 'queued'}:
unavailable_heartbeats = 0
unknown_heartbeats = 0
+ if state == 'queued':
+ set_server_stage(self.operator, 'Queued on Server')
+ elif not current_node:
+ set_server_stage(self.operator, 'Preparing Inputs')
print(f"[StableGen] No WebSocket event for {heartbeat}s; "
f"prompt is still {state} ({detail}). Continuing to wait.")
continue
@@ -461,31 +473,55 @@ class _WorkflowBase:
if isinstance(out, str):
message = json.loads(out)
+ data = message.get('data', {})
+ # Progress and errors can be broadcast by another queued job.
+ # Older servers omit prompt_id on progress; use its node below.
+ if data.get('prompt_id') not in (None, prompt_id):
+ continue
+
+ if message['type'] == 'execution_start':
+ set_server_stage(self.operator, 'Preparing Inputs')
- if message['type'] == 'executing':
+ elif message['type'] == 'executing':
data = message['data']
if data['prompt_id'] == prompt_id:
if data['node'] is None:
break # Execution is complete
else:
- current_node = data['node']
+ current_node = str(data['node'])
node_info = prompt.get(current_node, {})
node_title = (node_info.get('_meta', {}).get('title')
or node_info.get('class_type', current_node))
print(f"[StableGen] Executing node: {node_title} ({current_node})")
+ set_server_stage(self.operator, node_stage(current_node, node_info, NODES), node_title)
elif message['type'] == 'progress':
- progress = (message['data']['value'] / message['data']['max']) * 100
- if progress != 0:
- self.operator._progress = progress # Update progress for UI
- # Transition stage from "Uploading" to "Generating" on
- # first actual sampler progress from the server.
- if self.operator._stage == "Uploading to Server":
- self.operator._stage = "Generating Image"
+ event_node = data.get('node')
+ if not current_node or (event_node is not None and str(event_node) != current_node):
+ continue
+ try:
+ maximum = float(data.get('max', 0))
+ progress = float(data['value']) / maximum * 100 if maximum > 0 else None
+ except (KeyError, TypeError, ValueError):
+ continue
+ if progress is None or not 0 <= progress <= 100:
+ continue
+ node_info = prompt.get(current_node, {})
+ phase = node_stage(current_node, node_info, NODES)
+ sampling = phase == 'Starting Sampler'
+ if sampling and progress > 0:
+ phase = 'Generating Image'
+ set_server_stage(self.operator, phase,
+ getattr(self.operator, '_server_stage_detail', ''), progress)
+ if sampling:
+ # Keep per-image/overall sampling progress separate
+ # from encoder and other preprocessing progress.
+ self.operator._progress = progress
+ self.operator._server_step_text = f"Step {data['value']}/{data['max']}"
# Also update 3-tier detail when called from Trellis2Generate
if hasattr(self.operator, '_detail_progress'):
self.operator._detail_progress = progress
- self.operator._detail_stage = f"Step {message['data']['value']}/{message['data']['max']}"
+ self.operator._detail_stage = f"Step {data['value']}/{data['max']}"
# Remap progress into a sub-range when gallery mode is active
remap = getattr(self.operator, '_progress_remap', None)
if remap:
@@ -495,7 +531,7 @@ class _WorkflowBase:
self.operator._phase_progress = progress
if hasattr(self.operator, '_update_overall'):
self.operator._update_overall()
- print(f"[StableGen] Progress: {progress:.1f}%")
+ print(f"[StableGen] {phase}: {progress:.1f}%")
elif message['type'] == 'execution_error':
error_data = message.get('data', {})
@@ -535,6 +571,7 @@ class _WorkflowBase:
)
if needs_http and fallback_node_id:
+ set_server_stage(self.operator, 'Receiving Result', 'Downloading the generated image')
reason = "missing" if not ws_images else "corrupt"
print(f"[StableGen] WebSocket image data is {reason}. "
"Falling back to HTTP /history + /view download...")
@@ -579,8 +616,10 @@ class _WorkflowBase:
f"from output node {save_node!r}."
)
print(f"[StableGen] {self.operator._error}")
+ self.operator._server_stage = None
return {"error": "missing_output"}
+ self.operator._server_stage = None
return output_images
def _queue_prompt(self, prompt, client_id, server_address):