#
# Apache Lisansı, 2.0 Sürümü ("Lisans") altında lisanslanmıştır;
# bu dosyayı, Lisansa uygun olarak kullanabilirsiniz.
# Lisansın bir kopyasını şu adresten edinebilirsiniz
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Uygulanabilir yasa gerektirmedikçe veya yazılı olarak anlaşılmadıkça, yazılım
# Lisans kapsamında dağıtılan, "OLDUĞU GİBİ" esasına göre dağıtılır,
# HİÇBİR TÜR AÇIK VEYA ZIMMİ GARANTİ VEYA ŞART İÇERMEZ.
# İzinleri ve
# Lisans kapsamındaki kısıtlamalar.
-->

# VisualCloze

[VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning](https://huggingface.co/papers/2504.07960), bağlam içi öğrenmeye dayalı yenilikçi bir evrensel görüntü üretim çerçevesidir ve temel yetenekleri şunları sunar:
1. Çeşitli alan içi görevler için destek
2. Bağlam içi öğrenme yoluyla görülmemiş görevlere genelleme
3. Birden fazla görevi tek adımda birleştirin ve hem hedef görüntüyü hem de ara sonuçları üretin
4. Hedef görüntülerden tersine mühendislik koşullarını destekler

## Genel Bakış

Makalenin özeti şudur:

*Diffüzyon modellerindeki son ilerlemeler, çeşitli görüntü üretme görevlerinde önemli bir gelişme sağlamaktadır. Ancak, mevcut ana akım yaklaşım hâlâ görev-özel modellerin inşasına odaklanmaktadır ve bu modeller, geniş bir yelpazedeki farklı ihtiyaçları desteklerken sınırlı bir verimlilik göstermektedir. Evrensel modeller bu sınırlamayı ele almaya çalışsa da, genellenebilir görev talimatı, uygun görev dağılımları ve birleşik mimari tasarım gibi kritik zorluklarla karşı karşıyadır. Bu zorlukları ele almak için, geniş bir yelpazedeki alan içi görevleri, görülmemiş görevlere genelleme, birden fazla görevin görülmemiş birleşimini ve ters üretimi destekleyen, evrensel bir görüntü üretme çerçevesi olan VisualCloze'u öneriyoruz. Mevcut yöntemlerin aksine, görev belirsizliğine ve zayıf genelleme yeteneğine yol açan dil tabanlı görev talimatlarına dayanan bu yöntemlerin yerine, modellerin görevleri görsel gösterimlerden tanımlamasına olanak tanıyan görsel bağlam içi öğrenmeyi entegre ediyoruz. Bu arada, görsel görev dağılımlarının içsel seyrekliği, görevler arasında aktarılabilir bilginin öğrenmesini engellemektedir. Bu amaçla, çeşitli ilişkili görevler kuran, görev yoğunluğunu ve aktarılabilir bilgiyi artıran, grafik yapılı bir veri seti olan Graph200K'ı tanıtıyoruz. Ayrıca, birleşik görüntü üretme formülasyonumuzun görüntü doldurma ile tutarlı bir amaç paylaştığını ortaya koyduk; bu da, mimarileri değiştirmeden önceden eğitilmiş doldurma modellerinin güçlü üretken öncüllerinden yararlanmamızı mümkün kılmaktadır. Kodlar, veri seti ve modeller https://visualcloze.github.io adresinde mevcuttur.*

## Çıkarım

### Model yükleme

VisualCloze, `VisualClozeGenerationPipeline` ve `VisualClozeUpsamplingPipeline` içeren iki aşamalı bir kaskat hattıdır.
- `VisualClozeGenerationPipeline` içinde, her görüntü, görüntülerin bir ızgara düzenine birleştirilmeden önce aşırı yüksek çözünürlüklerden kaçınmak amacıyla örnekleme azaltılır (downsample). VisualCloze, diffusers için uygun iki model yayımlar: [VisualClozePipeline-384](https://huggingface.co/VisualCloze/VisualClozePipeline-384) ve [VisualClozePipeline-512](https://huggingface.co/VisualCloze/VisualClozePipeline-384); bu modeller görüntüleri sırasıyla 384 ve 512 çözünürlüklerine indirger.
- `VisualClozeUpsamplingPipeline`, yüksek çözünürlüklü görüntü sentezini mümkün kılmak için [SDEdit](https://huggingface.co/papers/2108.01073) kullanır.

`VisualClozePipeline`, her iki aşamayı bir araya getirerek kullanışlı uçtan uca örneklemeyi desteklerken, kullanıcıların ihtiyaçlarına göre her bir hattı bağımsız olarak kullanmasına da olanak tanır.

### Girdi Özellikleri

#### Görev ve İçerik İfadeleri
- Görev istemi: Üretim görevinin niyetini açıklamak için zorunludur
- İçerik istemi: Hedef görüntünün isteğe bağlı açıklaması veya altyazısı
- İçerik istemi gerekmediğinde `None` geçirin
- Toplu çıkarım için `List[str|None]` geçirin

#### Girdi Görüntü Biçimi
- Biçim: `List[List[Image|None]]`
- Yapı:
  - Son satır hariç tüm satırlar bağlam içi örnekleri temsil eder
  - Son satır, mevcut sorguyu temsil eder (hedef görüntü `None` olarak ayarlanır)
- Toplu çıkarım için `List[List[List[Image|None]]]` geçirin

#### Çözünürlük Kontrolü
- Varsayılan davranış:
  - İlk aşamadaki başlangıç üretimi: ${pipe.resolution}^2$ alanı
  - İkinci aşamada yukarı örneklem: 3x çarpan
- Özel çözünürlük: `upsampling_height` ve `upsampling_width` parametrelerini ayarlayarak değiştirin

### Örnekler

Geniş bir görev yelpazesini kapsayan kapsamlı örnekler için lütfen [Online Demo](https://huggingface.co/spaces/VisualCloze/VisualCloze) ve [GitHub Repository](https://github.com/lzyhha/VisualCloze) adreslerine bakın. Aşağıda maske-görüntüye dönüştürme, kenar algılama ve nesne odaklı üretim için üç durumun basit örnekleri yer almaktadır.

#### mask2image için örnek

```python
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image

pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
    # in-context examples
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg'),
    ],
    # query with the target image
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg'),
        None, # No image needed for the target image
    ],
]

# Task and content prompt
task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
content_prompt = """Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. 
The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. 
Its plumage is a mix of dark brown and golden hues, with intricate feather details. 
The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. 
The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, 
soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, 
tranquil, majestic, wildlife photography."""

# Run the pipeline
image_result = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    upsampling_width=1344,
    upsampling_height=768,
    upsampling_strength=0.4,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]

# Save the resulting image
image_result.save("visualcloze.png")
```

#### Kenar algılama için örnek

```python
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image

pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
    # in-context examples
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-1_image.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-1_edge.jpg'),
    ],
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-2_image.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-2_edge.jpg'),
    ],
    # query with the target image
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_query_image.jpg'),
        None, # No image needed for the target image
    ],
]

# Task and content prompt
task_prompt = "Each row illustrates a pathway from [IMAGE1] a sharp and beautifully composed photograph to [IMAGE2] edge map with natural well-connected outlines using a clear logical task."
content_prompt = ""

# Run the pipeline
image_result = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    upsampling_width=864,
    upsampling_height=1152,
    upsampling_strength=0.4,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]

# Save the resulting image
image_result.save("visualcloze.png")
```

#### Konu odaklı üretim için örnek

```python
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image

pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
    # in-context examples
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_reference.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_depth.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_image.jpg'),
    ],
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_reference.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_depth.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_image.jpg'),
    ],
    # query with the target image
    [
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_query_reference.jpg'),
        load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_query_depth.jpg'),
        None, # No image needed for the target image
    ],
]

# Task and content prompt
task_prompt = """Each row describes a process that begins with [IMAGE1] an image containing the key object, 
[IMAGE2] depth map revealing gray-toned spatial layers and results in 
[IMAGE3] an image with artistic qualitya high-quality image with exceptional detail."""
content_prompt = """A vintage porcelain collector's item. Beneath a blossoming cherry tree in early spring, 
this treasure is photographed up close, with soft pink petals drifting through the air and vibrant blossoms framing the scene."""

# Run the pipeline
image_result = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    upsampling_width=1024,
    upsampling_height=1024,
    upsampling_strength=0.2,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]

# Save the resulting image
image_result.save("visualcloze.png")
```

#### Her hattı bağımsız olarak kullanın 

```python
import torch
from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
from diffusers.utils import load_image
from PIL import Image

pipe = VisualClozeGenerationPipeline.from_pretrained(
    "VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image_paths = [
    # in-context examples
    [
        load_image(
            "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
        ),
        load_image(
            "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
        ),
    ],
    # query with the target image
    [
        load_image(
            "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
        ),
        None,  # No image needed for the target image
    ],
]
task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."

# Stage 1: Generate initial image
image = pipe(
    task_prompt=task_prompt,
    content_prompt=content_prompt,
    image=image_paths,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0),
).images[0][0]

# Stage 2 (optional): Upsample the generated image
pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
pipe_upsample.to("cuda")

mask_image = Image.new("RGB", image.size, (255, 255, 255))

image = pipe_upsample(
    image=image,
    mask_image=mask_image,
    prompt=content_prompt,
    width=1344,
    height=768,
    strength=0.4,
    guidance_scale=30,
    num_inference_steps=30,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0),
).images[0]

image.save("visualcloze.png")
```

## VisualClozePipeline[[diffusers.VisualClozePipeline]]

#### diffusers.VisualClozePipeline[[diffusers.VisualClozePipeline]]

```python
diffusers.VisualClozePipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, resolution: int = 384)
```

[Kaynak](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L89)

**Parametreler:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/tr/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : Kodlanmış görüntü latentlerini gürültüden arındırmak için kullanılan Koşullu Transformer (MMDiT) mimarisi.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/tr/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Kodlanmış görüntü latentlerini gürültüden arındırmak için `transformer` ile birlikte kullanılacak bir zamanlayıcı.

vae ([AutoencoderKL](/docs/diffusers/main/tr/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Görüntüleri gizil (latent) temsillere kodlamak ve bu temsillerden görüntülere çözmek için kullanılan Varyasyonel Oto-Kodlayıcı (VAE) Modeli.

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), özellikle [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) varyantı.

text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), özellikle [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) varyantı.

tokenizer (`CLIPTokenizer`) : [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) sınıfının tokenizer'ı.

tokenizer_2 (`T5TokenizerFast`) : [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) sınıfının ikinci Tokenizer'ı.

resolution (`int`, *isteğe bağlı*, varsayılan 384) : Sorgudan ve bağlam içi örneklerden görseller birleştirilirken her bir görselin çözünürlüğü.

Görsel bağlamla görüntü üretimi için VisualCloze hattı. Referans: https://github.com/lzyhha/VisualCloze/tree/main. Bu hat, görsel bağlam içi örneklerine dayalı olarak görüntü üretmek üzere tasarlanmıştır.

#### __call__[[diffusers.VisualClozePipeline.__call__]]

```python
__call__(task_prompt: str | list[str] = None, content_prompt: str | list[str] = None, image: typing.Optional[torch.FloatTensor] = None, upsampling_height: int | None = None, upsampling_width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 30.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, upsampling_strength: float = 1.0)
```

[Kaynak](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L252)

**Parametreler:**

task_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Görev niyetini tanımlamak için istem veya istemler.

content_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Üretilecek hedef görüntünün içeriğini veya başlığını tanımlamak için istem veya istemler.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]` veya `list[np.ndarray]`) : Başlangıç noktası olarak kullanılacak bir görüntü partisyonunu temsil eden `Image`, numpy dizisi veya tensör. Hem numpy dizisi hem de pytorch tensörü için beklenen değer aralığı `[0, 1]` arasındadır. Tensör veya tensör listesi olması durumunda beklenen şekil `(B, C, H, W)` veya `(C, H, W)` olmalıdır. Numpy dizisi veya dizi listesi olması durumunda beklenen şekil `(B, H, W, C)` veya `(H, W, C)` olmalıdır.

upsampling_height (`int`, *opsiyonel*, varsayılan olarak self.unet.config.sample_size * self.vae_scale_factor) : SDEdit ile yukarı örneklemeye (upsampling) tabi tutulduktan sonra üretilen (yani çıktı) görüntünün piksel cinsinden yüksekliği. Varsayılan olarak görüntü üç kat oranında yukarı örneklenir ve temel çözünürlük, hattın (pipeline) çözünürlük parametresi tarafından belirlenir. `upsampling_height` veya `upsampling_width` parametrelerinden yalnızca biri belirtildiğinde, diğeri en-boy oranına göre otomatik olarak ayarlanır.

upsampling_width (`int`, *opsiyonel*, varsayılan olarak self.unet.config.sample_size * self.vae_scale_factor) : SDEdit ile yukarı örneklemeye (upsampling) tabi tutulduktan sonra üretilen (yani çıktı) görüntünün piksel cinsinden genişliği. Varsayılan olarak görüntü üç kat oranında yukarı örneklenir ve temel çözünürlük, hattın (pipeline) çözünürlük parametresi tarafından belirlenir. `upsampling_height` veya `upsampling_width` parametrelerinden yalnızca biri belirtildiğinde, diğeri en-boy oranına göre otomatik olarak ayarlanır.

num_inference_steps (`int`, *isteğe bağlı*, varsayılan 50) : Gürültü azaltma adım sayısı. Daha fazla gürültü azaltma adımı genellikle daha yavaş çıkarım pahasına daha yüksek kaliteli bir görüntüye yol açar.

sigmas (`list[float]`, *isteğe bağlı*) : `set_timesteps` metodunda `sigmas` argümanını destekleyen zamanlayıcılarla gürültü azaltma süreci için kullanılacak özel sigmalar. Tanımlanmamışsa, `num_inference_steps` geçirildiğinde varsayılan davranış kullanılacaktır.

guidance_scale (`float`, *opsiyonel*, varsayılan 30.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)'de tanımlanan yönlendirme ölçeği. `guidance_scale`, [Imagen Paper](https://huggingface.co/papers/2205.11487)'deki 2. denklemindeki `w` olarak tanımlanır. Yönlendirme ölçeği, `guidance_scale > 1` olarak ayarlanarak etkinleştirilir. Daha yüksek yönlendirme ölçeği, genellikle daha düşük görüntü kalitesi pahasına, `prompt` ile yakından ilişkili görüntülerin üretilmesini teşvik eder.

num_images_per_prompt (`int`, *isteğe bağlı*, varsayılan 1) : Her istem için üretilecek görsel sayısı.

generator (`torch.Generator` veya `list[torch.Generator]`, *isteğe bağlı*) : Üretimi deterministik hale getirmek için bir veya [torch üreteci(leri)](https://pytorch.org/docs/stable/generated/torch.Generator.html) listesi.

latents (`torch.FloatTensor`, *isteğe bağlı*) : Görsel üretimi için girdi olarak kullanılacak, Gauss dağılımından örneklenmiş önceden oluşturulmuş gürültülü latensler. Farklı istemlerle aynı üretimi ayarlamak için kullanılabilir. Sağlanmazsa, sağlanan rastgele `generator` kullanılarak örneklemeye dayalı bir latens tensörü oluşturulur.

prompt_embeds (`torch.FloatTensor`, *isteğe bağlı*) : Ön oluşturulmuş metin gömme değerleri. Metin girdilerini kolayca ayarlamak için kullanılabilir, *ör.* istem ağırlıklandırması. Sağlanmazsa, metin gömme değerleri `prompt` girdi argümanından oluşturulur.

pooled_prompt_embeds (`torch.FloatTensor`, *isteğe bağlı*) : Önceden oluşturulmuş havuzlanmış metin gömme değerleri. Metin girdilerini kolayca ayarlamak için kullanılabilir, *ör.* istem ağırlıklandırması. Sağlanmazsa, havuzlanmış metin gömme değerleri `prompt` girdi argümanından oluşturulur.

output_type (`str`, *isteğe bağlı*, varsayılan `"pil"`) : Üretilen görüntünün çıktı biçimi. [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` veya `np.array` arasında seçim yapın.

return_dict (`bool`, *isteğe bağlı*, varsayılan `True`) : Düz bir tuple yerine `~pipelines.flux.FluxPipelineOutput` döndürülecek mi?

joint_attention_kwargs (`dict`, *isteğe bağlı*) : Belirtilirse, [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) içinde `self.processor` altında tanımlanan `AttentionProcessor`'a iletilen bir kwargs sözlüğü.

callback_on_step_end (`Callable`, *isteğe bağlı*) : Çıkarım sırasında her gürültü azaltma adımının sonunda çağrılan bir işlev. İşlev aşağıdaki argümanlarla çağrılır: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`, `callback_on_step_end_tensor_inputs` tarafından belirtilen tüm tensörlerin listesini içerir.

callback_on_step_end_tensor_inputs (`list`, *isteğe bağlı*) : `callback_on_step_end` işlevi için girdi tensörlerinin listesi. Listede belirtilen tensörler, `callback_kwargs` argümanı olarak geçirilir. Yalnızca pipeline sınıfınızın `._callback_tensor_inputs` özniteliğinde listelenen değişkenleri dahil edebilirsiniz.

max_sequence_length (`int` varsayılanı 512) : `prompt` ile kullanılacak maksimum dizi uzunluğu.

upsampling_strength (`float`, *opsiyonel*, varsayılan 1.0) : Sonuçlar büyütülürken referans `image`'in ne ölçüde dönüştürüleceğini belirtir. 0 ile 1 arasında olmalıdır. Üretilen görüntü bir başlangıç noktası olarak kullanılır ve `upsampling_strength` değeri arttıkça daha fazla gürültü eklenir. Gürültü azaltma adımlarının sayısı, başlangıçta eklenen gürültü miktarına bağlıdır. `upsampling_strength` 1 olduğunda eklenen gürültü maksimumdur ve gürültü azaltma süreci, `num_inference_steps` içinde belirtilen tam yineleme sayısı kadar çalışır. 0 değeri, büyütme adımını atlar ve sonuçları `self.resolution` çözünürlüğünde döndürür.

**Dönüş:** `~pipelines.flux.FluxPipelineOutput` veya `tuple`

`return_dict` True ise `~pipelines.flux.FluxPipelineOutput`, aksi halde bir `tuple`. Tuple döndürüldüğünde, ilk öğe üretilen görsellerin listesidir.

GörselCloze hattı için üretim çağrısı yapıldığında çağrılan işlev.

Örnekler:
```python
>>> import torch
>>> from diffusers import VisualClozePipeline
>>> from diffusers.utils import load_image

>>> image_paths = [
...     # in-context examples
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
...         ),
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
...         ),
...     ],
...     # query with the target image
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
...         ),
...         None,  # No image needed for the target image
...     ],
... ]
>>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
>>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
>>> pipe = VisualClozePipeline.from_pretrained(
...     "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = pipe(
...     task_prompt=task_prompt,
...     content_prompt=content_prompt,
...     image=image_paths,
...     upsampling_width=1344,
...     upsampling_height=768,
...     upsampling_strength=0.4,
...     guidance_scale=30,
...     num_inference_steps=30,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0][0]
>>> image.save("visualcloze.png")
```

## VisualClozeGenerationPipeline[[diffusers.VisualClozeGenerationPipeline]]

#### diffusers.VisualClozeGenerationPipeline[[diffusers.VisualClozeGenerationPipeline]]

```python
diffusers.VisualClozeGenerationPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, resolution: int = 384)
```

[Kaynak](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L118)

**Parametreler:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/tr/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : Kodlanmış görüntü latentlerini gürültüden arındırmak için kullanılan Koşullu Transformer (MMDiT) mimarisi.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/tr/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Kodlanmış görüntü latentlerini gürültüden arındırmak için `transformer` ile birlikte kullanılacak bir zamanlayıcı.

vae ([AutoencoderKL](/docs/diffusers/main/tr/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Görüntüleri gizil (latent) temsillere kodlamak ve bu temsillerden görüntülere çözmek için kullanılan Varyasyonel Oto-Kodlayıcı (VAE) Modeli.

text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), özellikle [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) varyantı.

text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), özellikle [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) varyantı.

tokenizer (`CLIPTokenizer`) : [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) sınıfının tokenizer'ı.

tokenizer_2 (`T5TokenizerFast`) : [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) sınıfının ikinci Tokenizer'ı.

resolution (`int`, *isteğe bağlı*, varsayılan 384) : Sorgudan ve bağlam içi örneklerden görseller birleştirilirken her bir görselin çözünürlüğü.

Görsel bağlamla görüntü üretimi için VisualCloze hattı. Referans: https://github.com/lzyhha/VisualCloze/tree/main Bu hat, görsel bağlam içi örneklerine dayalı olarak görüntü üretmek üzere tasarlanmıştır.

#### __call__[[diffusers.VisualClozeGenerationPipeline.__call__]]

```python
__call__(task_prompt: str | list[str] = None, content_prompt: str | list[str] = None, image: typing.Optional[torch.FloatTensor] = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 30.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)
```

[Kaynak](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L659)

**Parametreler:**

task_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Görev niyetini tanımlamak için istem veya istemler.

content_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Üretilecek hedef görüntünün içeriğini veya başlığını tanımlamak için istem veya istemler.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]` veya `list[np.ndarray]`) : Başlangıç noktası olarak kullanılacak bir görüntü partisyonunu temsil eden `Image`, numpy dizisi veya tensör. Hem numpy dizisi hem de pytorch tensörü için beklenen değer aralığı `[0, 1]` arasındadır. Tensör veya tensör listesi olması durumunda beklenen şekil `(B, C, H, W)` veya `(C, H, W)` olmalıdır. Numpy dizisi veya dizi listesi olması durumunda beklenen şekil `(B, H, W, C)` veya `(H, W, C)` olmalıdır.

num_inference_steps (`int`, *isteğe bağlı*, varsayılan 50) : Gürültü azaltma adım sayısı. Daha fazla gürültü azaltma adımı genellikle daha yavaş çıkarım pahasına daha yüksek kaliteli bir görüntüye yol açar.

sigmas (`list[float]`, *isteğe bağlı*) : `set_timesteps` metodunda `sigmas` argümanını destekleyen zamanlayıcılarla gürültü azaltma süreci için kullanılacak özel sigmalar. Tanımlanmamışsa, `num_inference_steps` geçirildiğinde varsayılan davranış kullanılacaktır.

guidance_scale (`float`, *opsiyonel*, varsayılan 30.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)'de tanımlanan yönlendirme ölçeği. `guidance_scale`, [Imagen Paper](https://huggingface.co/papers/2205.11487)'deki 2. denklemindeki `w` olarak tanımlanır. Yönlendirme ölçeği, `guidance_scale > 1` olarak ayarlanarak etkinleştirilir. Daha yüksek yönlendirme ölçeği, genellikle daha düşük görüntü kalitesi pahasına, `prompt` ile yakından ilişkili görüntülerin üretilmesini teşvik eder.

num_images_per_prompt (`int`, *isteğe bağlı*, varsayılan 1) : Her istem için üretilecek görsel sayısı.

generator (`torch.Generator` veya `list[torch.Generator]`, *isteğe bağlı*) : Üretimi deterministik hale getirmek için bir veya [torch üreteci(leri)](https://pytorch.org/docs/stable/generated/torch.Generator.html) listesi.

latents (`torch.FloatTensor`, *isteğe bağlı*) : Görsel üretimi için girdi olarak kullanılacak, Gauss dağılımından örneklenmiş önceden oluşturulmuş gürültülü latensler. Farklı istemlerle aynı üretimi ayarlamak için kullanılabilir. Sağlanmazsa, sağlanan rastgele `generator` kullanılarak örneklemeye dayalı bir latens tensörü oluşturulur.

prompt_embeds (`torch.FloatTensor`, *isteğe bağlı*) : Ön oluşturulmuş metin gömme değerleri. Metin girdilerini kolayca ayarlamak için kullanılabilir, *ör.* istem ağırlıklandırması. Sağlanmazsa, metin gömme değerleri `prompt` girdi argümanından oluşturulur.

pooled_prompt_embeds (`torch.FloatTensor`, *isteğe bağlı*) : Önceden oluşturulmuş havuzlanmış metin gömme değerleri. Metin girdilerini kolayca ayarlamak için kullanılabilir, *ör.* istem ağırlıklandırması. Sağlanmazsa, havuzlanmış metin gömme değerleri `prompt` girdi argümanından oluşturulur.

output_type (`str`, *isteğe bağlı*, varsayılan `"pil"`) : Üretilen görüntünün çıktı biçimi. `"pil"` ([PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image`), `"np"` (`np.array`) veya `"pt"` (`torch.Tensor`) arasında seçim yapın.

return_dict (`bool`, *isteğe bağlı*, varsayılan `True`) : Düz bir tuple yerine `~pipelines.flux.FluxPipelineOutput` döndürülecek mi?

joint_attention_kwargs (`dict`, *isteğe bağlı*) : Belirtilirse, [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) içinde `self.processor` altında tanımlanan `AttentionProcessor`'a iletilen bir kwargs sözlüğü.

callback_on_step_end (`Callable`, *isteğe bağlı*) : Çıkarım sırasında her gürültü azaltma adımının sonunda çağrılan bir işlev. İşlev aşağıdaki argümanlarla çağrılır: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`, `callback_on_step_end_tensor_inputs` tarafından belirtilen tüm tensörlerin listesini içerir.

callback_on_step_end_tensor_inputs (`list`, *isteğe bağlı*) : `callback_on_step_end` işlevi için girdi tensörlerinin listesi. Listede belirtilen tensörler, `callback_kwargs` argümanı olarak geçirilir. Yalnızca pipeline sınıfınızın `._callback_tensor_inputs` özniteliğinde listelenen değişkenleri dahil edebilirsiniz.

max_sequence_length (`int` varsayılanı 512) : `prompt` ile kullanılacak maksimum dizi uzunluğu.

**Dönüş:** `~pipelines.flux.FluxPipelineOutput` veya `tuple`

`return_dict` True ise `~pipelines.flux.FluxPipelineOutput`, aksi halde bir `tuple`. Tuple döndürüldüğünde, ilk öğe üretilen görsellerin listesidir.

GörselCloze hattı için üretim çağrısı yapıldığında çağrılan işlev.

Örnekler:
```python
>>> import torch
>>> from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
>>> from diffusers.utils import load_image
>>> from PIL import Image

>>> image_paths = [
...     # in-context examples
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
...         ),
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
...         ),
...     ],
...     # query with the target image
...     [
...         load_image(
...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
...         ),
...         None,  # No image needed for the target image
...     ],
... ]
>>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
>>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
>>> pipe = VisualClozeGenerationPipeline.from_pretrained(
...     "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = pipe(
...     task_prompt=task_prompt,
...     content_prompt=content_prompt,
...     image=image_paths,
...     guidance_scale=30,
...     num_inference_steps=30,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0][0]

>>> # optional, upsampling the generated image
>>> pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
>>> pipe_upsample.to("cuda")

>>> mask_image = Image.new("RGB", image.size, (255, 255, 255))

>>> image = pipe_upsample(
...     image=image,
...     mask_image=mask_image,
...     prompt=content_prompt,
...     width=1344,
...     height=768,
...     strength=0.4,
...     guidance_scale=30,
...     num_inference_steps=30,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0]

>>> image.save("visualcloze.png")
```

#### encode_prompt[[diffusers.VisualClozeGenerationPipeline.encode_prompt]]

```python
encode_prompt(layout_prompt: str | list[str], task_prompt: str | list[str], content_prompt: str | list[str], 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)
```

[Kaynak](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L292)

**Parametreler:**

layout_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Görevde yer alan bağlam içi örnek sayısını ve görsel sayısını tanımlamak için istem veya istemler.

task_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Görev niyetini tanımlamak için istem veya istemler.

content_prompt (`str` veya `list[str]`, *isteğe bağlı*) : Üretilecek hedef görüntünün içeriğini veya başlığını tanımlamak için istem veya istemler.

device : (`torch.device`): torch cihazı

num_images_per_prompt (`int`) : her istem için oluşturulacak görsel sayısı

prompt_embeds (`torch.FloatTensor`, *isteğe bağlı*) : Ön oluşturulmuş metin gömme değerleri. Metin girdilerini kolayca ayarlamak için kullanılabilir, *ör.* istem ağırlıklandırması. Sağlanmazsa, metin gömme değerleri `prompt` girdi argümanından oluşturulur.

pooled_prompt_embeds (`torch.FloatTensor`, *isteğe bağlı*) : Önceden oluşturulmuş havuzlanmış metin gömme değerleri. Metin girdilerini kolayca ayarlamak için kullanılabilir, *ör.* istem ağırlıklandırması. Sağlanmazsa, havuzlanmış metin gömme değerleri `prompt` girdi argümanından oluşturulur.

lora_scale (`float`, *isteğe bağlı*) : LoRA katmanları yüklendiyse, metin kodlayıcısının tüm LoRA katmanlarına uygulanacak bir lora ölçeği.

