This repository has been archived on 2026-10-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
imagelab_v3_extension/progress.py
T

135 lines
6.1 KiB
Python

import os
import sys
comfyui_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if comfyui_root not in sys.path:
sys.path.insert(0, comfyui_root)
from server import PromptServer
from io import BytesIO
from PIL import Image, ImageOps
import json
import struct
from protocol import BinaryEventTypes
# Custom binary event types for ImageLab
IMAGELAB_PROGRESS_EVENT = 100
IMAGELAB_PREVIEW_EVENT = 101
IMAGELAB_WORKFLOW_EVENT = 102
# Intercept send_sync FIRST (before creating handler that uses it)
# This is the KEY fix - hijack_progress in main.py sends "progress" and
# BinaryEventTypes.UNENCODED_PREVIEW_IMAGE directly to client_id, bypassing handlers.
# We need to intercept these and broadcast them to ALL clients.
_original_send_sync = PromptServer.instance.send_sync
_is_broadcasting = False # Prevent infinite recursion
def patched_send_sync(event, data, sid=None):
global _is_broadcasting
# Debug: Log what events we're seeing
if event == 'progress':
print(f"[ImageLab DEBUG] Intercepted 'progress' event: {data}")
elif event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
print(f"[ImageLab DEBUG] Intercepted UNENCODED_PREVIEW_IMAGE")
elif event == BinaryEventTypes.PREVIEW_IMAGE_WITH_METADATA:
print(f"[ImageLab DEBUG] Intercepted PREVIEW_IMAGE_WITH_METADATA")
# Always call original first
_original_send_sync(event, data, sid)
# Prevent infinite recursion when we broadcast
if _is_broadcasting:
return
try:
_is_broadcasting = True
# Broadcast workflow events to ALL clients
workflow_events = {'executing', 'execution_start', 'executed', 'execution_error', 'execution_cached'}
if event in workflow_events:
workflow_data = {'event': event, 'data': data}
_original_send_sync(IMAGELAB_WORKFLOW_EVENT, json.dumps(workflow_data).encode('utf-8'), sid=None)
# Broadcast "progress" event (sampler steps) to ALL clients
# This is sent by hijack_progress() in main.py only to client_id
elif event == 'progress' and isinstance(data, dict):
progress_data = {
'event': 'sampler_progress',
'node_id': data.get('node'),
'prompt_id': data.get('prompt_id'),
'value': data.get('value', 0),
'max': data.get('max', 1),
'progress_percent': round((data.get('value', 0) / data.get('max', 1) * 100), 2) if data.get('max', 1) > 0 else 0
}
_original_send_sync(IMAGELAB_PROGRESS_EVENT, json.dumps(progress_data).encode('utf-8'), sid=None)
# Broadcast preview images to ALL clients
# BinaryEventTypes.UNENCODED_PREVIEW_IMAGE is sent by hijack_progress() only to client_id
elif event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
# data is a tuple: (format, PIL.Image, max_size)
try:
img_format = data[0]
pil_image = data[1]
max_size = data[2] if len(data) > 2 else None
# Resize if needed
if max_size is not None:
if hasattr(Image, 'Resampling'):
resampling = Image.Resampling.BILINEAR
else:
resampling = Image.BILINEAR
pil_image = ImageOps.contain(pil_image, (max_size, max_size), resampling)
# Create metadata (we don't have node_id/prompt_id here, but server has last_node_id)
metadata = json.dumps({
'node_id': getattr(PromptServer.instance, 'last_node_id', None),
'prompt_id': getattr(PromptServer.instance, 'last_prompt_id', None)
}).encode('utf-8')
# Encode image
buffer = BytesIO()
pil_image.save(buffer, format=img_format, quality=95 if img_format == 'JPEG' else None, compress_level=1 if img_format == 'PNG' else None)
image_bytes = buffer.getvalue()
# Pack: metadata_length (4 bytes) + metadata + image
combined = struct.pack(">I", len(metadata)) + metadata + image_bytes
_original_send_sync(IMAGELAB_PREVIEW_EVENT, combined, sid=None)
except Exception as e:
print(f"[ImageLab] Preview broadcast error: {e}")
# Also broadcast PREVIEW_IMAGE_WITH_METADATA
elif event == BinaryEventTypes.PREVIEW_IMAGE_WITH_METADATA:
# data is a tuple: ((format, PIL.Image, max_size), metadata_dict)
try:
image_data, metadata = data
img_format = image_data[0]
pil_image = image_data[1]
max_size = image_data[2] if len(image_data) > 2 else None
# Resize if needed
if max_size is not None:
if hasattr(Image, 'Resampling'):
resampling = Image.Resampling.BILINEAR
else:
resampling = Image.BILINEAR
pil_image = ImageOps.contain(pil_image, (max_size, max_size), resampling)
# Encode metadata
metadata_bytes = json.dumps(metadata).encode('utf-8')
# Encode image
buffer = BytesIO()
pil_image.save(buffer, format=img_format, quality=95 if img_format == 'JPEG' else None, compress_level=1 if img_format == 'PNG' else None)
image_bytes = buffer.getvalue()
# Pack: metadata_length (4 bytes) + metadata + image
combined = struct.pack(">I", len(metadata_bytes)) + metadata_bytes + image_bytes
_original_send_sync(IMAGELAB_PREVIEW_EVENT, combined, sid=None)
except Exception as e:
print(f"[ImageLab] Preview metadata broadcast error: {e}")
except Exception as e:
print(f"[ImageLab] Broadcast error: {e}")
finally:
_is_broadcasting = False