The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.
[Partner Nodes] feat(Ideogram): add context window region editing to Ideogram 4.5 Precise Edit (#17428)
Alexander Piskun8c4f1f240426
diff --git a/comfy_api_nodes/apis/ideogram.py b/comfy_api_nodes/apis/ideogram.pyindex 7f2268be8..723eecd3c 100644--- a/comfy_api_nodes/apis/ideogram.py+++ b/comfy_api_nodes/apis/ideogram.py@@ -272,6 +272,7 @@ class Ideogram45Request(BaseModel):seed: int = Field(..., ge=0, le=2147483647)size: str | None = Nonemagic_prompt: str | None = None+ context_window: str | None = Noneclass IdeogramVectorGenerateRequest(BaseModel):diff --git a/comfy_api_nodes/nodes_ideogram.py b/comfy_api_nodes/nodes_ideogram.pyindex 5bb35f6a8..65c969336 100644--- a/comfy_api_nodes/nodes_ideogram.py+++ b/comfy_api_nodes/nodes_ideogram.py@@ -25,10 +25,12 @@ from comfy_api_nodes.util import (download_url_as_bytesio,download_url_to_image_tensor,downscale_image_tensor_by_max_side,+ pil_to_bytesio,poll_op,resize_mask_to_image,sync_op,tensor_to_bytesio,+ tensor_to_pil,validate_string,)from comfy_extras.nodes_images import SVG@@ -131,6 +133,8 @@ IDEOGRAM_45_MODELS = ["ideogram-4.5"]IDEOGRAM_45_MAX_IMAGES = 5IDEOGRAM_45_MAX_PIXELS = 4194304IDEOGRAM_45_MAX_SIDE = 4608+IDEOGRAM_45_MAX_SOURCE_PIXELS = 67108864+IDEOGRAM_45_MAX_UPLOAD_BYTES = 50000000IDEOGRAM_45_SIZES = ["(2K) 2048x2048 (1:1)","(2K) 1440x2880 (1:2)",@@ -755,7 +759,7 @@ def _resolve_image_refs(prompt: str, total_images: int) -> str:return "".join(parts)-def _ideogram_45_images(model: dict) -> list[torch.Tensor]:+def _ideogram_45_images(model: dict, check_first_aspect: bool) -> list[torch.Tensor]:images = [image for key in model["images"] for image in model["images"][key]]if len(images) > IDEOGRAM_45_MAX_IMAGES:raise ValueError(@@ -763,6 +767,8 @@ def _ideogram_45_images(model: dict) -> list[torch.Tensor]:f"(a batched input counts once per image).")for i, image in enumerate(images, start=1):+ if i == 1 and not check_first_aspect:+ continueheight, width = image.shape[0], image.shape[1]if max(width, height) > 6 * min(width, height):raise ValueError(f"Image {i} is {width}x{height}; its aspect ratio must be between 1:6 and 6:1.")@@ -783,6 +789,70 @@ def _ideogram_45_image_file(image: torch.Tensor) -> BytesIO:return tensor_to_bytesio(image, total_pixels=None, mime_type="image/png")+def _ideogram_45_full_size_file(image: torch.Tensor, max_bytes: int) -> tuple[str, BytesIO, str]:+ pil_image = tensor_to_pil(image, total_pixels=None)+ file = pil_to_bytesio(pil_image, mime_type="image/png")+ if file.getbuffer().nbytes <= max_bytes:+ return "image_1.png", file, "image/png"+ file = BytesIO()+ pil_image.convert("RGB").save(file, format="JPEG", quality=95)+ if file.getbuffer().nbytes > max_bytes:+ raise ValueError(+ "Image 1 together with context_window_mask and the reference images exceeds Ideogram's 50 MB upload "+ "limit; use fewer reference images."+ )+ file.seek(0)+ return "image_1.jpg", file, "image/jpeg"+++def _ideogram_45_mask_file(mask: torch.Tensor, image: torch.Tensor) -> BytesIO:+ mask = mask.reshape(-1, mask.shape[-2], mask.shape[-1])[:1]+ keep = (resize_mask_to_image(mask, image.unsqueeze(0))[0] <= 0.5).cpu().numpy()+ if keep.all() or not keep.any():+ raise ValueError("context_window_mask must mark both an area to edit (white) and an area to keep (black).")+ file = BytesIO()+ Image.fromarray(keep.astype(np.uint8) * 255).save(file, format="PNG")+ file.seek(0)+ return file+++def _ideogram_45_min_span(start: int, end: int, size: int, min_span: int) -> tuple[int, int]:+ if end - start >= min_span:+ return start, end+ start = min(max(0, (start + end - min_span) // 2), max(0, size - min_span))+ return start, min(size, start + min_span)+++def _ideogram_45_region(bboxes, width: int, height: int) -> str:+ if isinstance(bboxes, dict):+ boxes = [bboxes]+ elif bboxes and isinstance(bboxes[0], list):+ boxes = bboxes[0]+ else:+ boxes = bboxes+ if not boxes:+ raise ValueError("The context_window_bboxes input contains no bounding box.")+ x0 = max(0, min(round(b["x"]) for b in boxes))+ y0 = max(0, min(round(b["y"]) for b in boxes))+ x1 = min(width, max(round(b["x"] + b["width"]) for b in boxes))+ y1 = min(height, max(round(b["y"] + b["height"]) for b in boxes))+ if x1 <= x0 or y1 <= y0:+ raise ValueError(f"The bounding boxes lie outside image 1 ({width}x{height}).")+ x0, x1 = _ideogram_45_min_span(x0, x1, width, 256)+ y0, y1 = _ideogram_45_min_span(y0, y1, height, 256)+ x0, x1 = _ideogram_45_min_span(x0, x1, width, math.ceil((y1 - y0) / 6))+ y0, y1 = _ideogram_45_min_span(y0, y1, height, math.ceil((x1 - x0) / 6))+ w, h = x1 - x0, y1 - y0+ if max(w, h) > IDEOGRAM_45_MAX_SIDE or math.ceil(w / 32) * math.ceil(h / 32) * 1024 > IDEOGRAM_45_MAX_PIXELS:+ raise ValueError(+ f"Region {w}x{h} is too large; each side can be up to {IDEOGRAM_45_MAX_SIDE} pixels and the area "+ f"up to about 4 MP (e.g. 2048x2048)."+ )+ if max(w, h) > 6 * min(w, h):+ raise ValueError(f"Region {w}x{h} exceeds the maximum aspect ratio of 6:1.")+ return f"{y0},{x0},{y1},{x1}"++async def _ideogram_45_output(cls: type[IO.ComfyNode], response: IdeogramGenerateResponse) -> torch.Tensor:data = response.data or []urls = [item.url for item in data if item.url]@@ -875,6 +945,35 @@ def _ideogram_45_edit_inputs(with_size: bool) -> list:return inputs+def _ideogram_45_context_window_inputs() -> list:+ return [+ IO.Combo.Input(+ "context_window",+ options=["none", "auto", "custom"],+ default="none",+ optional=True,+ tooltip="Region of image 1 to edit. 'none' edits the whole image. 'auto' edits a region around "+ "context_window_mask, 'custom' the region from context_window_bboxes; both keep image 1 at full size "+ "and leave the rest unchanged.",+ ),+ IO.BoundingBox.Input(+ "context_window_bboxes",+ optional=True,+ force_input=True,+ tooltip="Region of image 1 to edit, e.g. from Create Bounding Boxes. Required when context_window is set "+ "to 'custom'; not used otherwise. Several boxes are merged into one region, which is enlarged to at least "+ "256 pixels per side and an aspect ratio of 6:1. The region can be up to 4608 pixels per side and about "+ "4 MP (e.g. 2048x2048).",+ ),+ IO.Mask.Input(+ "context_window_mask",+ optional=True,+ tooltip="White marks what to edit; the edit region is placed around it. Required when context_window is "+ "set to 'auto'; not used otherwise.",+ ),+ ]++def _ideogram_45_price_badge() -> IO.PriceBadge:return IO.PriceBadge(depends_on=IO.PriceBadgeDepends(widgets=["model", "model.quality"]),@@ -1010,7 +1109,7 @@ class IdeogramEditApi(IO.ComfyNode):@classmethodasync def execute(cls, model: dict):validate_string(model["prompt"], strip_whitespace=True, min_length=1, max_length=10000)- images = _ideogram_45_images(model)+ images = _ideogram_45_images(model, check_first_aspect=True)size = model["size"]if size == "custom":width, height = model["width"], model["height"]@@ -1050,12 +1149,15 @@ class IdeogramPreciseEditApi(IO.ComfyNode):category="partner/image/Ideogram",description="Edits an image guided by a text prompt using Ideogram 4.5 precise editing: only what the ""prompt asks for changes, untouched pixels stay identical and the output keeps the size of image 1 "- "(images above ~4 MP are scaled down first). Accepts up to 4 reference images.",+ "(images above ~4 MP are scaled down first). Can also edit a single region, set by a mask or bounding "+ "boxes, and return the image at full size. Accepts up to 4 reference images (3 with context_window_mask).",inputs=[IO.DynamicCombo.Input("model",options=[- IO.DynamicCombo.Option(model_id, _ideogram_45_edit_inputs(with_size=False))+ IO.DynamicCombo.Option(+ model_id, _ideogram_45_edit_inputs(with_size=False) + _ideogram_45_context_window_inputs()+ )for model_id in IDEOGRAM_45_MODELS],tooltip="Model to use.",@@ -1076,18 +1178,52 @@ class IdeogramPreciseEditApi(IO.ComfyNode):@classmethodasync def execute(cls, model: dict):validate_string(model["prompt"], strip_whitespace=True, min_length=1, max_length=10000)- images = _ideogram_45_images(model)+ context_window = model.get("context_window") or "none"+ mask = model.get("context_window_mask") if context_window == "auto" else None+ images = _ideogram_45_images(model, check_first_aspect=context_window == "none")prompt = _resolve_image_refs(model["prompt"], len(images))- files = [("image", ("image_1.png", _ideogram_45_image_file(images[0]), "image/png"))]+ height, width = images[0].shape[0], images[0].shape[1]+ if context_window != "none" and width * height > IDEOGRAM_45_MAX_SOURCE_PIXELS:+ raise ValueError(+ f"Image 1 is {width}x{height}; editing a region supports images up to "+ f"{IDEOGRAM_45_MAX_SOURCE_PIXELS} pixels (8192x8192)."+ )+ if context_window == "auto":+ if mask is None:+ raise ValueError("context_window 'auto' requires context_window_mask marking the area to edit.")+ if len(images) > IDEOGRAM_45_MAX_IMAGES - 1:+ raise ValueError(+ f"With context_window_mask, up to {IDEOGRAM_45_MAX_IMAGES - 2} reference images are supported; "+ f"got {len(images) - 1}."+ )+ elif context_window == "custom":+ bboxes = model.get("context_window_bboxes")+ if bboxes is None:+ raise ValueError("context_window 'custom' requires a context_window_bboxes input with the region to edit.")+ context_window = _ideogram_45_region(bboxes, width, height)+ files = []+ if mask is not None:+ files.append(("mask", ("mask.png", _ideogram_45_mask_file(mask, images[0]), "image/png")))files.extend(("reference_images", (f"image_{i}.png", _ideogram_45_image_file(image), "image/png"))for i, image in enumerate(images[1:], start=2))+ if context_window == "none":+ image_file = ("image_1.png", _ideogram_45_image_file(images[0]), "image/png")+ else:+ budget = IDEOGRAM_45_MAX_UPLOAD_BYTES - sum(f.getbuffer().nbytes for _, (_, f, _) in files)+ image_file = _ideogram_45_full_size_file(images[0], budget)+ files.insert(0, ("image", image_file))response = await sync_op(cls,ApiEndpoint(path=IDEOGRAM_45_PRECISE_EDIT_PATH, method="POST"),response_model=IdeogramGenerateResponse,- data=Ideogram45Request(prompt=prompt, quality=model["quality"], seed=model["seed"]),+ data=Ideogram45Request(+ prompt=prompt,+ quality=model["quality"],+ seed=model["seed"],+ context_window=None if context_window == "none" else context_window,+ ),files=files,content_type="multipart/form-data",)@@ -1187,7 +1323,7 @@ class IdeogramVectorGenerateApi(IO.ComfyNode):@classmethodasync def execute(cls, model: dict):validate_string(model["prompt"], strip_whitespace=True, min_length=1, max_length=9500)- images = _ideogram_45_images(model)+ images = _ideogram_45_images(model, check_first_aspect=True)prompt = _resolve_image_refs(model["prompt"], len(images))aspect_ratio = model["aspect_ratio"]response = await sync_op(