Skip to content

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(Bria): add new image edit nodes and the Video Eraser node (#16264)

Alexander Piskunc75d8c966c29
diff --git a/comfy_api_nodes/apis/bria.py b/comfy_api_nodes/apis/bria.py
index f55de74bc..a48eea567 100644
--- a/comfy_api_nodes/apis/bria.py
+++ b/comfy_api_nodes/apis/bria.py
@@ -217,3 +217,148 @@ class BriaVideoReplaceBackgroundRequest(BaseModel):
output_container_and_codec: str = Field(...)
preserve_audio: bool = Field(True)
seed: int = Field(...)
+
+
+class BriaEraseByTextRequest(BaseModel):
+ image: str = Field(...)
+ object_name: str = Field(..., description="Name of the object to remove, for example 'the lamp'.")
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaReplaceBackgroundRequest(BaseModel):
+ image: str = Field(...)
+ prompt: str | None = Field(
+ None,
+ description="Description of the new background. Mutually exclusive with ref_images; "
+ "a hex color code produces a solid color background.",
+ )
+ ref_images: list[str] | None = Field(
+ None,
+ description="Reference images guiding the new background. Mutually exclusive with prompt.",
+ )
+ mode: str | None = Field(
+ None, description="'base', 'high_control' or 'fast'. Applies to the prompt path only."
+ )
+ refine_prompt: bool | None = Field(
+ None, description="When true, the prompt is rewritten for better results. Prompt path only."
+ )
+ enhance_ref_images: bool | None = Field(
+ None, description="When true, the reference images get extra processing. Reference path only."
+ )
+ original_quality: bool = Field(
+ False,
+ description="When true, the output keeps the input's pixel size; otherwise it is scaled to 1MP.",
+ )
+ seed: int = Field(...)
+ prompt_content_moderation: bool = Field(False, description="If true, returns 422 on prompt moderation failure.")
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaEraseForegroundRequest(BaseModel):
+ image: str = Field(...)
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaAddObjectRequest(BaseModel):
+ image: str = Field(...)
+ instruction: str = Field(
+ ..., description="What to add and where, for example 'Place a red vase with flowers on the table'."
+ )
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaReplaceObjectRequest(BaseModel):
+ image: str = Field(...)
+ instruction: str = Field(
+ ..., description="What to replace with what, for example 'Replace the red apple with a green pear'."
+ )
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaRelightRequest(BaseModel):
+ image: str = Field(...)
+ light_type: str = Field(..., description="Lighting atmosphere to apply.")
+ light_direction: str = Field(..., description="Where the light comes from: front, side, bottom or top-down.")
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaRestoreRequest(BaseModel):
+ image: str = Field(...)
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaReseasonRequest(BaseModel):
+ image: str = Field(...)
+ season: str = Field(..., description="Season to apply: spring, summer, autumn or winter.")
+ visual_input_content_moderation: bool = Field(
+ False, description="If true, returns 422 on input image moderation failure."
+ )
+ visual_output_content_moderation: bool = Field(
+ False, description="If true, returns 422 on visual output moderation failure."
+ )
+
+
+class BriaVideoEraseRequest(BaseModel):
+ video: str = Field(..., description="Publicly accessible URL of the input video.")
+ mask: str = Field(
+ ...,
+ description="Publicly accessible URL of a mask video: white pixels are erased, black pixels are kept. "
+ "Must have the same dimensions and frame count as the input video.",
+ )
+ preserve_audio: bool = Field(True)
+ output_container_and_codec: str = Field(...)
+
+
+class BriaFiboEditResult(BaseModel):
+ image_url: str = Field(...)
+ structured_prompt: str | None = Field(None)
+
+
+class BriaFiboEditResponse(BaseModel):
+ status: str = Field(...)
+ result: BriaFiboEditResult | None = Field(None)
+
+
+class BriaReplaceBackgroundResult(BaseModel):
+ image_url: str = Field(...)
+ refined_prompt: str | None = Field(None)
+
+
+class BriaReplaceBackgroundResponse(BaseModel):
+ status: str = Field(...)
+ result: BriaReplaceBackgroundResult | None = Field(None)
diff --git a/comfy_api_nodes/nodes_bria.py b/comfy_api_nodes/nodes_bria.py
index 90cade2d0..3c2866e2a 100644
--- a/comfy_api_nodes/nodes_bria.py
+++ b/comfy_api_nodes/nodes_bria.py
@@ -1,23 +1,35 @@
import av
import torch
from av.codec import CodecContext
+from pydantic import BaseModel
from typing_extensions import override
-from comfy_api.latest import IO, ComfyExtension, Input
+from comfy_api.latest import IO, ComfyExtension, Input, Types, VideoFromComponents
from comfy_api_nodes.apis.bria import (
+ BriaAddObjectRequest,
BriaEditImageRequest,
+ BriaEraseByTextRequest,
+ BriaEraseForegroundRequest,
BriaEraseRequest,
BriaExpandRequest,
BriaExpandResponse,
+ BriaFiboEditResponse,
BriaGenFillRequest,
BriaImageEditResponse,
BriaImageResultResponse,
BriaIncreaseResolutionRequest,
+ BriaRelightRequest,
BriaRemoveBackgroundRequest,
BriaRemoveBackgroundResponse,
BriaRemoveVideoBackgroundRequest,
BriaRemoveVideoBackgroundResponse,
+ BriaReplaceBackgroundRequest,
+ BriaReplaceBackgroundResponse,
+ BriaReplaceObjectRequest,
+ BriaReseasonRequest,
+ BriaRestoreRequest,
BriaStatusResponse,
+ BriaVideoEraseRequest,
BriaVideoGreenScreenRequest,
BriaVideoReplaceBackgroundRequest,
InputModerationSettings,
@@ -32,6 +44,7 @@ from comfy_api_nodes.util import (
poll_op,
sync_op,
upload_image_to_comfyapi,
+ upload_images_to_comfyapi,
upload_video_to_comfyapi,
validate_string,
validate_video_duration,
@@ -276,11 +289,13 @@ def _mask_to_binary_image(mask: Input.Image, action: str) -> torch.Tensor:
return convert_mask_to_image(binary)
-def _validate_mask_aspect_ratio(image: Input.Image, mask: Input.Image) -> None:
- ih, iw = image.shape[1], image.shape[2]
+def _validate_mask_aspect_ratio(mask: Input.Image, width: int, height: int, subject: str = "image") -> None:
mh, mw = mask.shape[-2], mask.shape[-1]
- if abs(iw * mh - ih * mw) > 0.01 * ih * mw:
- raise ValueError(f"Mask must have the same aspect ratio as the image: image is {iw}x{ih}, mask is {mw}x{mh}.")
+ if abs(width * mh - height * mw) > 0.01 * height * mw:
+ raise ValueError(
+ f"Mask must have the same aspect ratio as the {subject}: "
+ f"{subject} is {width}x{height}, mask is {mw}x{mh}."
+ )
class BriaGenFill(IO.ComfyNode):
@@ -362,7 +377,7 @@ class BriaGenFill(IO.ComfyNode):
moderation: InputModerationSettings,
) -> IO.NodeOutput:
validate_string(prompt, min_length=1)
- _validate_mask_aspect_ratio(image, mask)
+ _validate_mask_aspect_ratio(mask, image.shape[2], image.shape[1])
mask_image = _mask_to_binary_image(mask, "fill")
response = await sync_op(
cls,
@@ -449,7 +464,7 @@ class BriaEraser(IO.ComfyNode):
mask_type: str,
moderation: dict,
) -> IO.NodeOutput:
- _validate_mask_aspect_ratio(image, mask)
+ _validate_mask_aspect_ratio(mask, image.shape[2], image.shape[1])
mask_image = _mask_to_binary_image(mask, "erase")
response = await sync_op(
cls,
@@ -1086,6 +1101,734 @@ class BriaTransparentVideoBackground(IO.ComfyNode):
return IO.NodeOutput(images, mask)
+BRIA_LIGHT_TYPES = [
+ "midday",
+ "blue hour light",
+ "low-angle sunlight",
+ "sunrise light",
+ "spotlight on subject",
+ "overcast light",
+ "soft overcast daylight lighting",
+ "cloud-filtered lighting",
+ "fog-diffused lighting",
+ "moonlight lighting",
+ "starlight nighttime",
+ "soft bokeh lighting",
+ "harsh studio lighting",
+]
+BRIA_LIGHT_DIRECTIONS = ["front", "side", "bottom", "top-down"]
+BRIA_SEASONS = ["spring", "summer", "autumn", "winter"]
+BRIA_FAILED_STATUSES = ["error", "unknown"]
+BRIA_MAX_REFERENCE_IMAGES = 10
+BRIA_VIDEO_ERASE_MAX_DURATION = 5.1
+BRIA_VIDEO_ERASE_MIN_FPS = 20
+BRIA_VIDEO_ERASE_MAX_FPS = 30
+BRIA_FIBO_EDIT_NOTE = (
+ "Bria re-renders the whole frame at about 1 megapixel, so the result is not pixel-aligned with the input."
+)
+
+
+def _moderation_combo(*flags: str) -> IO.DynamicCombo.Input:
+ return IO.DynamicCombo.Input(
+ "moderation",
+ options=[
+ IO.DynamicCombo.Option("false", []),
+ IO.DynamicCombo.Option("true", [IO.Boolean.Input(flag, default=False) for flag in flags]),
+ ],
+ tooltip="Moderation settings",
+ )
+
+
+def _visual_moderation(moderation: InputModerationSettings) -> tuple[bool, bool]:
+ return (
+ moderation.get("visual_input_moderation", False),
+ moderation.get("visual_output_moderation", False),
+ )
+
+
+def _drop_alpha(image: Input.Image) -> torch.Tensor:
+ return image[..., :3]
+
+
+def _structured_prompt_output() -> IO.String.Output:
+ return IO.String.Output(
+ id="structured_prompt",
+ display_name="structured_prompt",
+ tooltip="Structured description of the edited image, for a follow-up edit with Bria FIBO Image Edit.",
+ )
+
+
+async def _poll_bria(cls: type[IO.ComfyNode], request_id: str, response_model: type[BaseModel]):
+ return await poll_op(
+ cls,
+ ApiEndpoint(path=f"/proxy/bria/v2/status/{request_id}"),
+ status_extractor=lambda r: r.status,
+ failed_statuses=BRIA_FAILED_STATUSES,
+ response_model=response_model,
+ )
+
+
+async def _run_fibo_edit(cls: type[IO.ComfyNode], path: str, data: BaseModel) -> IO.NodeOutput:
+ submitted = await sync_op(
+ cls,
+ ApiEndpoint(path=path, method="POST"),
+ data=data,
+ response_model=BriaStatusResponse,
+ )
+ response = await _poll_bria(cls, submitted.request_id, BriaFiboEditResponse)
+ return IO.NodeOutput(
+ await download_url_to_image_tensor(response.result.image_url),
+ response.result.structured_prompt or "",
+ )
+
+
+class BriaEraseByText(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaEraseByText",
+ display_name="Bria Erase by Text",
+ category="partner/image/Bria",
+ description="Remove an object named in plain text from an image using Bria. " + BRIA_FIBO_EDIT_NOTE,
+ inputs=[
+ IO.Image.Input("image"),
+ IO.String.Input(
+ "object_name",
+ default="",
+ tooltip="Name of the object to remove, such as 'the lamp'. Several objects can be named "
+ "at once, such as 'the phone and the pencils'. Naming something that is not in the "
+ "picture still returns, and bills, a re-rendered image.",
+ ),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output(), _structured_prompt_output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(
+ cls,
+ image: Input.Image,
+ object_name: str,
+ moderation: InputModerationSettings,
+ ) -> IO.NodeOutput:
+ validate_string(object_name, field_name="object_name", min_length=1)
+ visual_input, visual_output = _visual_moderation(moderation)
+ return await _run_fibo_edit(
+ cls,
+ "/proxy/bria/v2/image/edit/erase_by_text",
+ BriaEraseByTextRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ object_name=object_name,
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ )
+
+
+class BriaAddObject(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaAddObject",
+ display_name="Bria Add Object",
+ category="partner/image/Bria",
+ description="Insert an object described in plain text into an image using Bria. " + BRIA_FIBO_EDIT_NOTE,
+ inputs=[
+ IO.Image.Input("image"),
+ IO.String.Input(
+ "instruction",
+ multiline=True,
+ default="",
+ tooltip="What to add and where, such as 'Place a red vase with flowers on the table'.",
+ ),
+ IO.Int.Input(
+ "seed",
+ default=42,
+ min=0,
+ max=2147483647,
+ step=1,
+ display_mode=IO.NumberDisplay.number,
+ control_after_generate=True,
+ tooltip="Bria takes no seed here and re-imagines the edit on each call, so repeated runs can differ. The value is never sent: it only changes this node's cache key, so that an otherwise identical graph runs the edit again instead of returning the cached result.",
+ ),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output(), _structured_prompt_output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(
+ cls,
+ image: Input.Image,
+ instruction: str,
+ seed: int,
+ moderation: InputModerationSettings,
+ ) -> IO.NodeOutput:
+ validate_string(instruction, field_name="instruction", min_length=1)
+ visual_input, visual_output = _visual_moderation(moderation)
+ return await _run_fibo_edit(
+ cls,
+ "/proxy/bria/v2/image/edit/add_object_by_text",
+ BriaAddObjectRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ instruction=instruction,
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ )
+
+
+class BriaReplaceObject(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaReplaceObject",
+ display_name="Bria Replace Object",
+ category="partner/image/Bria",
+ description="Swap an object in an image for another one described in plain text using Bria. "
+ + BRIA_FIBO_EDIT_NOTE,
+ inputs=[
+ IO.Image.Input("image"),
+ IO.String.Input(
+ "instruction",
+ multiline=True,
+ default="",
+ tooltip="What to replace with what, such as 'Replace the red apple with a green pear'.",
+ ),
+ IO.Int.Input(
+ "seed",
+ default=42,
+ min=0,
+ max=2147483647,
+ step=1,
+ display_mode=IO.NumberDisplay.number,
+ control_after_generate=True,
+ tooltip="Bria takes no seed here and re-imagines the edit on each call, so repeated runs can differ. The value is never sent: it only changes this node's cache key, so that an otherwise identical graph runs the edit again instead of returning the cached result.",
+ ),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output(), _structured_prompt_output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(
+ cls,
+ image: Input.Image,
+ instruction: str,
+ seed: int,
+ moderation: InputModerationSettings,
+ ) -> IO.NodeOutput:
+ validate_string(instruction, field_name="instruction", min_length=1)
+ visual_input, visual_output = _visual_moderation(moderation)
+ return await _run_fibo_edit(
+ cls,
+ "/proxy/bria/v2/image/edit/replace_object_by_text",
+ BriaReplaceObjectRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ instruction=instruction,
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ )
+
+
+class BriaRelight(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaRelight",
+ display_name="Bria Relight",
+ category="partner/image/Bria",
+ description="Change the lighting atmosphere and direction of an image using Bria. "
+ + BRIA_FIBO_EDIT_NOTE,
+ inputs=[
+ IO.Image.Input("image"),
+ IO.Combo.Input(
+ "light_type",
+ options=BRIA_LIGHT_TYPES,
+ tooltip="Lighting atmosphere to apply.",
+ ),
+ IO.Combo.Input(
+ "light_direction",
+ options=BRIA_LIGHT_DIRECTIONS,
+ tooltip="Where the light comes from. Hard-light atmospheres such as midday, "
+ "spotlight on subject and harsh studio lighting react to it the most.",
+ ),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output(), _structured_prompt_output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(
+ cls,
+ image: Input.Image,
+ light_type: str,
+ light_direction: str,
+ moderation: InputModerationSettings,
+ ) -> IO.NodeOutput:
+ visual_input, visual_output = _visual_moderation(moderation)
+ return await _run_fibo_edit(
+ cls,
+ "/proxy/bria/v2/image/edit/relight",
+ BriaRelightRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ light_type=light_type,
+ light_direction=light_direction,
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ )
+
+
+class BriaRestorePhoto(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaRestorePhoto",
+ display_name="Bria Restore Photo",
+ category="partner/image/Bria",
+ description="Repair an old or damaged photograph with Bria: grain, scratches and blur go, and "
+ "age-related color casts are neutralized. Card mounts and studio borders may be cropped away and "
+ "faces are re-drawn. " + BRIA_FIBO_EDIT_NOTE + " Use Bria Increase Resolution to enlarge instead.",
+ inputs=[
+ IO.Image.Input("image"),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output(), _structured_prompt_output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(cls, image: Input.Image, moderation: InputModerationSettings) -> IO.NodeOutput:
+ visual_input, visual_output = _visual_moderation(moderation)
+ return await _run_fibo_edit(
+ cls,
+ "/proxy/bria/v2/image/edit/restore",
+ BriaRestoreRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ )
+
+
+class BriaReseason(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaReseason",
+ display_name="Bria Reseason",
+ category="partner/image/Bria",
+ description="Move an image to another season with Bria. The whole scene is re-rendered, so "
+ "scenery can change beyond the season itself. " + BRIA_FIBO_EDIT_NOTE,
+ inputs=[
+ IO.Image.Input("image"),
+ IO.Combo.Input("season", options=BRIA_SEASONS, tooltip="Season to apply."),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output(), _structured_prompt_output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(cls, image: Input.Image, season: str, moderation: InputModerationSettings) -> IO.NodeOutput:
+ visual_input, visual_output = _visual_moderation(moderation)
+ return await _run_fibo_edit(
+ cls,
+ "/proxy/bria/v2/image/edit/reseason",
+ BriaReseasonRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ season=season,
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ )
+
+
+class BriaEraseForeground(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaEraseForeground",
+ display_name="Bria Erase Foreground",
+ category="partner/image/Bria",
+ description="Remove the foreground of an image with Bria and generate a background in its place. "
+ "Everything Bria reads as foreground goes, not only people. The untouched pixels are preserved, "
+ "but the output is re-rendered at a standard size close to 1 megapixel.",
+ inputs=[
+ IO.Image.Input("image"),
+ _moderation_combo("visual_input_moderation", "visual_output_moderation"),
+ ],
+ outputs=[IO.Image.Output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(cls, image: Input.Image, moderation: InputModerationSettings) -> IO.NodeOutput:
+ visual_input, visual_output = _visual_moderation(moderation)
+ submitted = await sync_op(
+ cls,
+ ApiEndpoint(path="/proxy/bria/v2/image/edit/erase_foreground", method="POST"),
+ data=BriaEraseForegroundRequest(
+ image=await upload_image_to_comfyapi(cls, _drop_alpha(image), wait_label="Uploading image"),
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ response_model=BriaStatusResponse,
+ )
+ response = await _poll_bria(cls, submitted.request_id, BriaImageResultResponse)
+ return IO.NodeOutput(await download_url_to_image_tensor(response.result.image_url))
+
+
+class BriaReplaceImageBackground(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaReplaceImageBackground",
+ display_name="Bria Replace Image Background",
+ category="partner/image/Bria",
+ description="Replace the background of an image with Bria, described by a prompt or guided by "
+ "reference images. The subject's pixels are preserved; the background is generated around them.",
+ inputs=[
+ IO.Image.Input("image"),
+ IO.DynamicCombo.Input(
+ "background",
+ options=[
+ IO.DynamicCombo.Option(
+ "prompt",
+ [
+ IO.String.Input(
+ "prompt",
+ multiline=True,
+ default="",
+ tooltip="Description of the new background. A hex color code such as "
+ "#FF5733 produces a solid color background.",
+ ),
+ IO.Combo.Input(
+ "mode",
+ options=["high_control", "base", "fast"],
+ tooltip="high_control follows the prompt most closely, base is a "
+ "balanced default and fast trades detail for speed.",
+ ),
+ IO.Boolean.Input(
+ "refine_prompt",
+ default=True,
+ tooltip="Rewrite the prompt for better results, which also translates "
+ "non-English prompts. Turn it off to send the prompt exactly as written.",
+ ),
+ ],
+ ),
+ IO.DynamicCombo.Option(
+ "reference images",
+ [
+ IO.Autogrow.Input(
+ "ref_images",
+ template=IO.Autogrow.TemplateNames(
+ IO.Image.Input("ref_image"),
+ names=[f"ref_image_{i}" for i in range(1, BRIA_MAX_REFERENCE_IMAGES + 1)],
+ min=1,
+ ),
+ tooltip=f"1-{BRIA_MAX_REFERENCE_IMAGES} images guiding the new background; "
+ "they do not need to share a size. Every reference changes the result, so "
+ "a few consistent ones beat many conflicting ones. A batched input counts "
+ "once per image.",
+ ),
+ IO.Boolean.Input(
+ "enhance_ref_images",
+ default=True,
+ tooltip="Extra processing of the reference images for better results.",
+ ),
+ ],
+ ),
+ ],
+ tooltip="Describe the new background with a prompt, or guide it with reference images.",
+ ),
+ IO.Boolean.Input(
+ "original_quality",
+ default=False,
+ tooltip="Return the input's exact pixel size instead of scaling the result to about "
+ "1 megapixel. A large input then returns a large image.",
+ ),
+ IO.Int.Input(
+ "seed",
+ default=42,
+ min=0,
+ max=2147483647,
+ step=1,
+ display_mode=IO.NumberDisplay.number,
+ control_after_generate=True,
+ tooltip="The same seed usually returns the same background; the automatic prompt "
+ "refinement can still vary it.",
+ ),
+ _moderation_combo(
+ "prompt_content_moderation", "visual_input_moderation", "visual_output_moderation"
+ ),
+ ],
+ outputs=[
+ IO.Image.Output(),
+ IO.String.Output(
+ id="refined_prompt",
+ display_name="refined_prompt",
+ tooltip="The prompt Bria generated from, empty on the reference-image path.",
+ ),
+ ],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.0572}',
+ ),
+ )
+
+ @classmethod
+ async def execute(
+ cls,
+ image: Input.Image,
+ background: dict,
+ original_quality: bool,
+ seed: int,
+ moderation: InputModerationSettings,
+ ) -> IO.NodeOutput:
+ prompt = None
+ ref_images = None
+ mode = None
+ refine_prompt = None
+ enhance_ref_images = None
+ if background["background"] == "prompt":
+ prompt = background["prompt"]
+ validate_string(prompt, field_name="prompt", min_length=1)
+ mode = background["mode"]
+ refine_prompt = background["refine_prompt"]
+ else:
+ references = [
+ _drop_alpha(image)
+ for images in background["ref_images"].values()
+ if images is not None
+ for image in images
+ ]
+ if len(references) > BRIA_MAX_REFERENCE_IMAGES:
+ raise ValueError(
+ f"At most {BRIA_MAX_REFERENCE_IMAGES} reference images are supported, got {len(references)}."
+ )
+ ref_images = await upload_images_to_comfyapi(
+ cls,
+ references,
+ max_images=BRIA_MAX_REFERENCE_IMAGES,
+ wait_label="Uploading reference images",
+ )
+ enhance_ref_images = background["enhance_ref_images"]
+ visual_input, visual_output = _visual_moderation(moderation)
+ submitted = await sync_op(
+ cls,
+ ApiEndpoint(path="/proxy/bria/v2/image/edit/replace_background", method="POST"),
+ data=BriaReplaceBackgroundRequest(
+ image=await upload_image_to_comfyapi(
+ cls,
+ _drop_alpha(image),
+ total_pixels=None if original_quality else 2048 * 2048,
+ wait_label="Uploading image",
+ ),
+ prompt=prompt,
+ ref_images=ref_images,
+ mode=mode,
+ refine_prompt=refine_prompt,
+ enhance_ref_images=enhance_ref_images,
+ original_quality=original_quality,
+ seed=seed,
+ prompt_content_moderation=moderation.get("prompt_content_moderation", False),
+ visual_input_content_moderation=visual_input,
+ visual_output_content_moderation=visual_output,
+ ),
+ response_model=BriaStatusResponse,
+ )
+ response = await _poll_bria(cls, submitted.request_id, BriaReplaceBackgroundResponse)
+ return IO.NodeOutput(
+ await download_url_to_image_tensor(response.result.image_url),
+ response.result.refined_prompt or "",
+ )
+
+
+class BriaVideoEraser(IO.ComfyNode):
+
+ @classmethod
+ def define_schema(cls):
+ return IO.Schema(
+ node_id="BriaVideoEraser",
+ display_name="Bria Video Eraser",
+ category="partner/video/Bria",
+ description="Erase whatever a per-frame mask covers from a video with Bria and fill the gap in. "
+ "The mask must be white on what should go and black elsewhere. Bria accepts clips of at most "
+ "5.1 seconds at 20 to 30 frames per second with even pixel dimensions; audio is kept by default. "
+ "The returned clip can be a few frames shorter than the input.",
+ inputs=[
+ IO.Video.Input("video", tooltip="Clip to erase from."),
+ IO.Mask.Input(
+ "mask",
+ optional=True,
+ tooltip="One mask per frame of the video, white where the object to erase is. "
+ "Provide either a mask or a mask video, not both.",
+ ),
+ IO.Video.Input(
+ "mask_video",
+ optional=True,
+ tooltip="An already encoded mask video with the same dimensions and frame count as the "
+ "video. Provide either a mask or a mask video, not both.",
+ ),
+ IO.Boolean.Input("preserve_audio", default=True, tooltip="Keep the input's audio track."),
+ ],
+ outputs=[IO.Video.Output()],
+ hidden=[
+ IO.Hidden.auth_token_comfy_org,
+ IO.Hidden.api_key_comfy_org,
+ IO.Hidden.unique_id,
+ ],
+ is_api_node=True,
+ price_badge=IO.PriceBadge(
+ expr='{"type":"usd","usd":0.06435,"format":{"suffix":"/second"}}',
+ ),
+ )
+
+ @classmethod
+ async def execute(
+ cls,
+ video: Input.Video,
+ preserve_audio: bool,
+ mask: Input.Mask | None = None,
+ mask_video: Input.Video | None = None,
+ ) -> IO.NodeOutput:
+ if mask is None and mask_video is None:
+ raise ValueError("Connect either a mask or a mask video.")
+ if mask is not None and mask_video is not None:
+ raise ValueError("Provide either a mask or a mask video, not both.")
+ validate_video_duration(video, max_duration=BRIA_VIDEO_ERASE_MAX_DURATION)
+ width, height = video.get_dimensions()
+ if width % 2 or height % 2:
+ raise ValueError(
+ f"Bria needs even pixel dimensions, but the video is {width}x{height}. Crop or scale it first."
+ )
+ frame_count = video.get_frame_count()
+ frame_rate = video.get_frame_rate()
+ if not BRIA_VIDEO_ERASE_MIN_FPS <= float(frame_rate) <= BRIA_VIDEO_ERASE_MAX_FPS:
+ raise ValueError(
+ f"Bria accepts {BRIA_VIDEO_ERASE_MIN_FPS} to {BRIA_VIDEO_ERASE_MAX_FPS} frames per second, "
+ f"but the video runs at {float(frame_rate):.3f}. Re-time it with Get Video Components and "
+ f"Create Video first."
+ )
+ if mask is not None:
+ if mask.shape[0] != frame_count:
+ raise ValueError(
+ f"The mask has {mask.shape[0]} frame(s) but the video has {frame_count}; "
+ f"Bria needs one mask frame per video frame."
+ )
+ _validate_mask_aspect_ratio(mask, width, height, "video")
+ if mask.shape[-1] != width or mask.shape[-2] != height:
+ mask = torch.nn.functional.interpolate(
+ mask.unsqueeze(1).float(), size=(height, width), mode="nearest-exact"
+ )[:, 0]
+ mask_source = VideoFromComponents(
+ Types.VideoComponents(images=_mask_to_binary_image(mask, "erase"), frame_rate=frame_rate)
+ )
+ else:
+ mask_width, mask_height = mask_video.get_dimensions()
+ mask_frame_count = mask_video.get_frame_count()
+ if (mask_width, mask_height) != (width, height):
+ raise ValueError(
+ f"The mask video must have the same dimensions as the video: video is {width}x{height}, "
+ f"mask video is {mask_width}x{mask_height}."
+ )
+ if mask_frame_count != frame_count:
+ raise ValueError(
+ f"The mask video has {mask_frame_count} frames but the video has {frame_count}; "
+ f"Bria needs one mask frame per video frame."
+ )
+ mask_source = mask_video
+ submitted = await sync_op(
+ cls,
+ ApiEndpoint(path="/proxy/bria/v2/video/edit/erase", method="POST"),
+ data=BriaVideoEraseRequest(
+ video=await upload_video_to_comfyapi(cls, video),
+ mask=await upload_video_to_comfyapi(cls, mask_source, wait_label="Uploading mask"),
+ preserve_audio=preserve_audio,
+ output_container_and_codec="mp4_h264",
+ ),
+ response_model=BriaStatusResponse,
+ )
+ response = await _poll_bria(cls, submitted.request_id, BriaRemoveVideoBackgroundResponse)
+ return IO.NodeOutput(await download_url_to_video_output(response.result.video_url))
+
+
class BriaExtension(ComfyExtension):
@override
async def get_node_list(self) -> list[type[IO.ComfyNode]]:
@@ -1100,6 +1843,15 @@ class BriaExtension(ComfyExtension):
BriaVideoGreenScreen,
BriaVideoReplaceBackground,
BriaTransparentVideoBackground,
+ BriaEraseByText,
+ BriaAddObject,
+ BriaReplaceObject,
+ BriaRelight,
+ BriaRestorePhoto,
+ BriaReseason,
+ BriaEraseForeground,
+ BriaReplaceImageBackground,
+ BriaVideoEraser,
]