# FluxControlInpaint

  

FluxControlInpaintPipeline는 Flux.1 Depth/Canny 모델을 위한 Inpainting 구현체입니다. Flux.1 Depth/Canny 모델을 사용하여 이미지를 inpaint할 수 있는 파이프라인입니다. 이 파이프라인은 이미지와 마스크를 입력으로 받아 inpaint된 이미지를 반환합니다.

FLUX.1 Depth and Canny [dev]은 120억 개의 파라미터를 가진 rectified flow transformer로, 텍스트 설명을 기반으로 이미지를 생성하는 동시에 주어진 입력 이미지의 구조를 따릅니다. **이것은 ControlNet 모델이 아닙니다**.

| 제어 유형 | 개발자 | 링크 |
| -------- | ---------- | ---- |
| 깊이 | [Black Forest Labs](https://huggingface.co/black-forest-labs) | [링크](https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev) |
| Canny | [Black Forest Labs](https://huggingface.co/black-forest-labs) | [링크](https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev) |

> [!TIP]
> Flux는 소비자용 하드웨어에서 실행할 때 비용이 상당히 높을 수 있습니다. 그러나 일련의 최적화를 수행하여 더 빠르고 메모리에 부담이 적은 방식으로 실행할 수 있습니다. 자세한 내용은 [이 섹션](https://huggingface.co/blog/sd3#memory-optimizations-for-sd3)을 확인하세요. 또한, Flux는 추론 지연 시간의 트레이드오프를 감수하고 메모리 효율성을 위해 양자화를 활용할 수 있습니다. 더 자세한 내용은 [이 블로그 게시물](https://huggingface.co/blog/quanto-diffusers)을 참고하세요. 포괄적인 리소스 목록은 [이 gist](https://gist.github.com/sayakpaul/b664605caf0aa3bf8585ab109dd5ac9c)에서 확인하세요.

```python
import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np

pipe = FluxControlInpaintPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Depth-dev",
    dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

head_mask = np.zeros_like(image)
head_mask[65:580,300:642] = 255
mask_image = Image.fromarray(head_mask)

processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")

output = pipe(
    prompt=prompt,
    image=image,
    control_image=control_image,
    mask_image=mask_image,
    num_inference_steps=30,
    strength=0.9,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save("output.png")
```

## FluxControlInpaintPipeline[[diffusers.FluxControlInpaintPipeline]]

#### diffusers.FluxControlInpaintPipeline[[diffusers.FluxControlInpaintPipeline]]

```python
diffusers.FluxControlInpaintPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L204)

**매개변수:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/ko/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer (MMDiT) 아키텍처.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`와 함께 사용하여 인코딩된 이미지 라텐트를 디노이즈하는 데 사용되는 스케줄러입니다.

vae ([AutoencoderKL](/docs/diffusers/main/ko/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다.

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형입니다.

text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) 변형입니다.

tokenizer (`CLIPTokenizer`) : [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) 클래스의 토크나이저.

tokenizer_2 (`T5TokenizerFast`) : [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) 클래스의 두 번째 Tokenizer.

Flux-dev-Depth/Canny를 사용하여 이미지 인페인팅을 수행하는 Flux 파이프라인입니다.

참고: https://blackforestlabs.ai/announcing-black-forest-labs/

#### __호출__[[diffusers.FluxControlInpaintPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.6, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L753)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2`와 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우 `prompt`가 대신 사용됩니다

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : 시작점으로 사용할 이미지 배치의 `Image`, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는 `[0, 1]`입니다. 텐서 또는 텐서 목록인 경우, 예상 shape은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. numpy 배열 또는 배열 목록인 경우, 예상 shape은 `(B, H, W, C)` 또는 `(H, W, C)`여야 합니다. `image`로 이미지 latents도 받을 수 있지만, latents를 직접 전달하는 경우 다시 인코딩되지 않습니다.

control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` 또는 `list[list[PIL.Image.Image]]`): 생성 시 `unet`에 가이드를 제공하기 위한 ControlNet 입력 조건입니다. 타입이 `torch.Tensor`로 지정된 경우, ControlNet에 그대로 전달됩니다. `PIL.Image.Image`도 이미지로 허용됩니다. 출력 이미지의 차원은 기본적으로 `image`의 차원을 따릅니다. height와/또는 width가 전달되면, `image`는 이에 맞게 리사이즈됩니다. `init`에서 여러 ControlNet이 지정된 경우, 각 ControlNet에 대한 입력이 올바르게 배치(batch)될 수 있도록 리스트의 각 요소가 이미지가 되도록 리스트로 전달해야 합니다.

mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : `image`를 마스킹할 이미지 배치(`Image`, numpy 배열 또는 텐서)를 나타냅니다. 마스크의 흰색 픽셀은 다시 채워지고 검은색 픽셀은 유지됩니다. `mask_image`가 PIL 이미지인 경우, 사용 전에 단일 채널(명도)로 변환됩니다. numpy 배열 또는 pytorch 텐서인 경우 3개 대신 하나의 색상 채널(L)을 포함해야 하므로, pytorch 텐서의 예상 shape은 `(B, 1, H, W)`, `(B, H, W)`, `(1, H, W)`, `(H, W)`입니다. numpy 배열의 경우 `(B, H, W, 1)`, `(B, H, W)`, `(H, W, 1)`, 또는 `(H, W)`입니다.

masked_image_latents (`torch.Tensor`, `list[torch.Tensor]`) : VAE가 생성한 `image`를 마스킹할 이미지 배치(`Tensor`)를 나타냅니다. 제공되지 않으면 `mask_image`에 의해 마스킹된 잠재 텐서가 생성됩니다.

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 1024로 설정됩니다.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 너비입니다. 최적의 결과를 위해 기본값은 1024로 설정됩니다.

strength (`float`, *선택 사항*, 기본값 1.0) : 참조 `image`를 변환할 정도를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되며, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 기본적으로 `image`를 무시하는 것과 같습니다.

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.

sigmas (`list[float]`, *선택 사항*) : `set_timesteps` 메서드에 `sigmas` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다.

guidance_scale (`float`, *선택 사항*, 기본값 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)에서 정의한 가이던스 스케일입니다. `guidance_scale`은 [Imagen Paper](https://huggingface.co/papers/2205.11487)의 2번 식의 `w`로 정의됩니다. `guidance_scale > 1`을 설정하여 가이던스 스케일을 활성화합니다. 가이던스 스케일이 높을수록 `prompt` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.

num_images_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 이미지의 수.

generator (`torch.Generator` 또는 `list[torch.Generator]`, *선택 사항*) : 생성을 결정적으로 만들기 위한 [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.FloatTensor`, *선택 사항*) : 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈된 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링하여 latents 텐서가 생성됩니다.

prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

pooled_prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.

output_type (`str`, *선택 사항*, 기본값 `"pil"`) : 이미지 생성의 출력 형식입니다. [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` 또는 `np.array` 중 하나를 선택합니다.

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `~pipelines.flux.FluxPipelineOutput`을 반환할지 여부.

joint_attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.

callback_on_step_end (`Callable`, *선택 사항*) : 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`에는 `callback_on_step_end_tensor_inputs`로 지정된 모든 텐서 목록이 포함됩니다.

callback_on_step_end_tensor_inputs (`list`, *선택 사항*) : `callback_on_step_end` 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 `callback_kwargs` 인수로 전달됩니다. 파이프라인 클래스의 `._callback_tensor_inputs` 속성에 나열된 변수만 포함할 수 있습니다.

max_sequence_length (`int` 기본값은 512) : `prompt`에 사용할 최대 시퀀스 길이입니다.

**반환값:** `~pipelines.flux.FluxPipelineOutput` 또는 `tuple`

`return_dict`가 True인 경우 `~pipelines.flux.FluxPipelineOutput`, 그렇지 않으면 `tuple`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 목록입니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:
```py
import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor  # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np

pipe = FluxControlInpaintPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Depth-dev",
    torch_dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")

prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

head_mask = np.zeros_like(image)
head_mask[65:580, 300:642] = 255
mask_image = Image.fromarray(head_mask)

processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")

output = pipe(
    prompt=prompt,
    image=image,
    control_image=control_image,
    mask_image=mask_image,
    num_inference_steps=30,
    strength=0.9,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save(
    "output.png"
)
```

#### encode_prompt[[diffusers.FluxControlInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L376)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우 모든 text-encoder에 `prompt`가 사용됩니다.

device : (`torch.device`): torch 디바이스

num_images_per_prompt (`int`) : 프롬프트당 생성할 이미지 수

prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

pooled_prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.

lora_scale (`float`, *선택 사항*) : LoRA 레이어가 로드된 경우, 텍스트 인코더의 모든 LoRA 레이어에 적용될 LoRA 스케일입니다.

## FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]

#### diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]

```python
diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_output.py#L11)

**매개변수:**

images (`list[PIL.Image.Image]` 또는 `torch.Tensor` 또는 `np.ndarray`) : 길이가 `batch_size`인 노이즈 제거된 PIL 이미지 목록 또는 `(batch_size, height, width, num_channels)` 모양의 numpy 배열 또는 torch 텐서입니다. PIL 이미지 또는 numpy 배열은 diffusion 파이프라인의 노이즈 제거된 이미지를 나타냅니다. Torch 텐서는 노이즈 제거된 이미지 또는 디코더로 전달할 준비가 된 중간 latents를 나타낼 수 있습니다.

Flux 이미지 생성 파이프라인의 출력 클래스입니다.

