#
# مرخّص بموجب ترخيص Apache الإصدار 2.0 (المسمى "الترخيص")
# لا يجوز لك استخدام هذا الملف إلا وفقاً لشروط الترخيص.
# يمكنك الحصول على نسخة من الترخيص في
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# ما لم يقتضِ ذلك القانون المعمول به أو ما اتُّفق عليه كتابياً، البرمجيات
# تُوزَّع بموجب الرخصة على أساس "كما هي"،
# بلا أي ضمانات أو شروط من أي نوع، سواء صريحة أو ضمنية.
# راجع الترخيص لمعرفة اللغة المحددة التي تحكم الصلاحيات و
# الشروط المحددة في الترخيص.
-->

# VisualCloze

[VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning](https://huggingface.co/papers/2504.07960) هو إطار شامل مبتكر لتوليد الصور يعتمد على التعلم السياقي البصري، ويوفر قدرات رئيسية:
1. دعم لمهام متنوعة ضمن المجال
2. التعميم على مهام غير مرئية من خلال التعلم في السياق
3. توحيد المهام المتعددة في خطوة واحدة وتوليد الصورة المستهدفة والنتائج الوسيطة معًا
4. دعم استنتاج الشروط من الصور المستهدفة

## نظرة عامة

ملخص الورقة البحثية هو:

*أحدثت التطورات الأخيرة في نماذج الانتشار تقدماً كبيراً في مهام توليد الصور المختلفة. ومع ذلك، لا يزال النهج السائد حالياً يركّز على بناء نماذج مخصصة لكل مهمة، وهي نماذج ذات كفاءة محدودة عند دعم مجموعة واسعة من الاحتياجات المختلفة. وعلى الرغم من أن النماذج الشاملة تحاول معالجة هذه القصور، فإنها تواجه تحديات جوهرية، من بينها تعليمات المهام القابلة للتعميم، وتوزيعات المهام المناسبة، والتصميم المعماري الموحّد. لمعالجة هذه التحديات، نقترح VisualCloze، وهو إطار شامل لتوليد الصور، يدعم مجموعة واسعة من المهام ضمن المجال، والتعميم على مهام غير مرئية، والدمج غير المرئي لعدة مهام، والتوليد العكسي. وعلى عكس الأساليب القائمة التي تعتمد على تعليمات المهام اللغوية، مما يؤدي إلى غموض في المهام وضعف في التعميم، ندمج التعلّم البصري في السياق، مما يتيح للنماذج تحديد المهام من خلال أمثلة بصرية. وفي الوقت نفسه، يعيق التناثر الجوهري لتوزيعات المهام البصرية تعلّم المعرفة القابلة للنقل بين المهام. لهذا الغرض، نقدّم Graph200K، وهو مجموعة بيانات ذات بنية شبكية تُنشئ مهام متشابكة متنوعة، مما يعزز كثافة المهام والمعرفة القابلة للنقل. علاوة على ذلك، اكتشفنا أن صياغة توليد الصور الموحّدة لدينا تتشارك هدفاً متسقاً مع ملء الصور، مما مكّننا من الاستفادة من الأسبقيات التوليدية القوية لنماذج الملء المُدرَّبة مسبقاً دون تعديل البنى المعمارية. الكود ومجموعة البيانات والنماذج متاحة على https://visualcloze.github.io.*

## الاستدلال

### تحميل النموذج

VisualCloze هو خط أنابيب متسلسل من مرحلتين، يتضمن `VisualClozeGenerationPipeline` و`VisualClozeUpsamplingPipeline`.
- في `VisualClozeGenerationPipeline`، يتم تقليل دقة كل صورة قبل دمج الصور في تخطيط شبكي، لتجنب الدقات العالية بشكل مفرط. تُصدر VisualCloze نموذجين مناسبين لـ diffusers، وهما [VisualClozePipeline-384](https://huggingface.co/VisualCloze/VisualClozePipeline-384) و[VisualClozePipeline-512](https://huggingface.co/VisualCloze/VisualClozePipeline-384)، حيث تقلل دقة الصور إلى 384 و512 على التوالي.
- `VisualClozeUpsamplingPipeline` يستخدم [SDEdit](https://huggingface.co/papers/2108.01073) لتمكين تركيب الصور عالية الدقة.

تدمج `VisualClozePipeline` كلا المرحلتين لدعم أخذ عينات مريح من البداية إلى النهاية، مع السماح للمستخدمين في الوقت نفسه باستخدام كل خط أنابيب بشكل مستقل حسب الحاجة.

### مواصفات الإدخال

#### موجّهات المهام والمحتوى
- مهمة الأمر: مطلوب وصف نية مهمة التوليد
- موجّه المحتوى: وصف أو تعليق اختياري للصورة المستهدفة
- عند عدم الحاجة إلى موجه المحتوى، مرّر `None`
- للاستدلال الدفعي، مرّر `List[str|None]`

#### صيغة إدخال الصورة
- الصيغة: `List[List[Image|None]]`
- البنية:
  - تمثّل جميع الصفوف باستثناء الصف الأخير أمثلة ضمن السياق
  - تمثل الصف الأخير الاستعلام الحالي (تم تعيين مجموعة الصور المستهدفة إلى `None`)
- للاستدلال الدفعي، مرر `List[List[List[Image|None]]]`

#### التحكم في الدقة
- السلوك الافتراضي:
  - المرحلة الأولى من التوليد الأولي: مساحة ${pipe.resolution}^2$
  - الرفع في المرحلة الثانية: عامل 3x
- دقة مخصصة: اضبط باستخدام معاملي `upsampling_height` و`upsampling_width`

### أمثلة

لمزيد من الأمثلة الشاملة التي تغطي مجموعة واسعة من المهام، يُرجى الرجوع إلى [العرض التوضيحي عبر الإنترنت](https://huggingface.co/spaces/VisualCloze/VisualCloze) و[مستودع GitHub](https://github.com/lzyhha/VisualCloze). فيما يلي أمثلة بسيطة لثلاث حالات: تحويل القناع إلى صورة، وكشف الحواف، والتوليد الموجه بالموضوع.

#### مثال على mask2image

```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")
```

#### مثال على كشف الحواف

```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")
```

#### مثال على التوليد الموجّه بالموضوع

```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")
```

#### استخدم كل خط أنابيب بشكل مستقل 

```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)
```

[المصدر](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L89)

**المعاملات:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/ar/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : معمارية Transformer الشرطية (MMDiT) لإزالة الضوضاء من الكامنات المُرمّزة للصورة.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ar/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : مُجدوِل يُستخدم بالاقتران مع `transformer` لإزالة الضوضاء من كامنات الصورة المُرمَّزة.

vae ([AutoencoderKL](/docs/diffusers/main/ar/api/models/autoencoderkl#diffusers.AutoencoderKL)) : نموذج الترميز التحويلي التبايني (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).

resolution (`int`، *اختياري*، القيمة الافتراضية 384) : دقة كل صورة عند دمج الصور من الاستعلام والأمثلة السياقية.

خط أنابيب VisualCloze لتوليد الصور مع سياق بصري. المرجع: https://github.com/lzyhha/VisualCloze/tree/main. صُمم هذا الخط أنابيب لتوليد الصور بناءً على أمثلة سياقية بصرية.

#### __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)
```

[المصدر](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py#L252)

**المعاملات:**

task_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر لتحديد نية المهمة.

content_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر لتحديد محتوى الصورة المستهدفة أو وصفها الذي سيتم توليده.

image (`torch.Tensor`، `PIL.Image.Image`، `np.ndarray`، `list[torch.Tensor]`، `list[PIL.Image.Image]`، أو `list[np.ndarray]`) : `Image`، مصفوفة numpy أو tensor تمثل دفعة من الصور (image batch) لاستخدامها كنقطة انطلاق. لكل من مصفوفة numpy وtensor الخاص بـ pytorch، النطاق المتوقع للقيم هو بين `[0, 1]` إذا كان tensor أو قائمة من tensors، فيجب أن يكون الشكل المتوقع `(B, C, H, W)` أو `(C, H, W)`. أما إذا كانت مصفوفة numpy أو قائمة من المصفوفات، فيجب أن يكون الشكل المتوقع `(B, H, W, C)` أو `(H, W, C)`.

upsampling_height (`int`, *اختياري*، القيمة الافتراضية هي self.unet.config.sample_size * self.vae_scale_factor) : ارتفاع الصورة المولَّدة (أي الصورة الناتجة) بالبكسلات بعد إعادة الترميز عبر SDEdit. افتراضيًا، تتم إعادة ترميز الصورة بمعامل ثلاثة، ويُحدَّد الدقة الأساسية بواسطة معامل الدقة في خط الأنابيب. عند تحديد واحد فقط من `upsampling_height` أو `upsampling_width`، يُضبط الآخر تلقائيًا بناءً على نسبة الأبعاد.

upsampling_width (`int`, *اختياري*، القيمة الافتراضية هي self.unet.config.sample_size * self.vae_scale_factor) : عرض الصورة المولَّدة (أي الصورة الناتجة) بالبكسل بعد إعادة الترميز عبر SDEdit. افتراضيًا، تتم إعادة ترميز الصورة بمعامل ثلاثة، ويُحدَّد الدقة الأساسية بواسطة معامل الدقة في خط الأنابيب. عند تحديد واحد فقط من `upsampling_height` أو `upsampling_width`، يُضبط الآخر تلقائيًا بناءً على نسبة الأبعاد.

num_inference_steps (`int`، *اختياري*، القيمة الافتراضية 50) : عدد خطوات إزالة الضوضاء. تؤدي زيادة عدد خطوات إزالة الضوضاء عادةً إلى صورة ذات جودة أعلى على حساب بطء الاستدلال.

sigmas (`list[float]`، *اختياري*) : قيم `sigmas` مخصصة لاستخدامها في عملية إزالة الضوضاء مع المجدولين الذين يدعمون معامل `sigmas` في طريقة `set_timesteps` الخاصة بهم. إذا لم تُعرَّف، فسيتم استخدام السلوك الافتراضي عند تمرير `num_inference_steps`.

guidance_scale (`float`، *اختياري*، القيمة الافتراضية 30.0) : مقياس التوجيه كما هو مُعرَّف في [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). يُعرَّف `guidance_scale` على أنه `w` من المعادلة 2. في [Imagen Paper](https://huggingface.co/papers/2205.11487). يتم تفعيل مقياس التوجيه عن طريق تعيين `guidance_scale > 1`. يشجع مقياس التوجيه الأعلى على توليد صور مرتبطة ارتباطًا وثيقًا بنص `prompt`، وعادةً على حساب انخفاض جودة الصورة.

num_images_per_prompt (`int`، *اختياري*، القيمة الافتراضية 1) : عدد الصور التي سيتم توليدها لكل موجه.

generator (`torch.Generator` أو `list[torch.Generator]`، *اختياري*) : مولّد واحد أو قائمة من [مولّدات torch](https://pytorch.org/docs/stable/generated/torch.Generator.html) لجعل التوليد حتميًا.

latents (`torch.FloatTensor`، *اختياري*) : كامنات ضجيج مُولّدة مسبقًا، مُستخرجة من توزيع غاوسي، تُستخدم كمدخلات لتوليد الصور. يمكن استخدامها لتعديل نفس التوليد باستخدام أوامر مختلفة. إذا لم تُقدَّم، فسيتم إنشاء كامنات من خلال الاستخراج باستخدام `generator` العشوائي المُقدَّم.

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` بدلاً من tuple عادي.

joint_attention_kwargs (`dict`، *اختياري*) : قاموس kwargs يُمرَّر إلى `AttentionProcessor` إذا تم تحديده، كما هو معرَّف تحت `self.processor` في [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

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`، *اختياري*) : قائمة مدخلات المصفوفات (tensors) لدالة `callback_on_step_end`. سيتم تمرير المصفوفات المحددة في القائمة كحجة `callback_kwargs`. لن تتمكن من تضمين سوى المتغيرات المدرجة في خاصية `._callback_tensor_inputs` لفئة خط الأنابيب (pipeline) الخاص بك.

max_sequence_length (`int` الافتراضي 512) : أقصى طول تسلسل يُستخدم مع `prompt`.

upsampling_strength (`float`, *اختياري*، القيمة الافتراضية 1.0) : يحدد مدى تحويل الصورة المرجعية `image` عند رفع عينة النتائج. يجب أن يكون بين 0 و 1. تُستخدم الصورة المولّدة كنقطة انطلاق، وكلما ارتفعت قيمة `upsampling_strength` زاد مقدار الضوضاء المضافة. يعتمد عدد خطوات إزالة الضوضاء على كمية الضوضاء المضافة في البداية. عندما تكون قيمة `upsampling_strength` هي 1، تكون الضوضاء المضافة في أقصى حد، وتعمل عملية إزالة الضوضاء لعدد التكرارات الكامل المحدد في `num_inference_steps`. القيمة 0 تتخطى خطوة رفع العينة وتُخرج النتائج بدقة `self.resolution`.

**يعيد:** `~pipelines.flux.FluxPipelineOutput` أو `tuple`

`~pipelines.flux.FluxPipelineOutput` إذا كان `return_dict` هو True، وإلا `tuple`. عند إرجاع tuple، يكون العنصر الأول قائمة تحتوي على الصور المولّدة.

الدالة التي تُستدعى عند استدعاء خط أنابيب VisualCloze للتوليد.

أمثلة:
```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)
```

[المصدر](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L118)

**المعاملات:**

transformer ([FluxTransformer2DModel](/docs/diffusers/main/ar/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : معمارية Transformer الشرطية (MMDiT) لإزالة الضوضاء من الكامنات المُرمّزة للصورة.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ar/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : مُجدوِل يُستخدم بالاقتران مع `transformer` لإزالة الضوضاء من كامنات الصورة المُرمَّزة.

vae ([AutoencoderKL](/docs/diffusers/main/ar/api/models/autoencoderkl#diffusers.AutoencoderKL)) : نموذج الترميز التحويلي التبايني (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).

resolution (`int`، *اختياري*، القيمة الافتراضية 384) : دقة كل صورة عند دمج الصور من الاستعلام والأمثلة السياقية.

خط أنابيب VisualCloze لتوليد الصور مع سياق بصري. المرجع: https://github.com/lzyhha/VisualCloze/tree/main صُمم هذا الخط أنابيب لتوليد الصور بناءً على أمثلة سياقية بصرية.

#### __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)
```

[المصدر](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L659)

**المعاملات:**

task_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر لتحديد نية المهمة.

content_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر لتحديد محتوى الصورة المستهدفة أو وصفها الذي سيتم توليده.

image (`torch.Tensor`، `PIL.Image.Image`، `np.ndarray`، `list[torch.Tensor]`، `list[PIL.Image.Image]`، أو `list[np.ndarray]`) : `Image`، مصفوفة numpy أو tensor تمثل دفعة من الصور (image batch) لاستخدامها كنقطة انطلاق. لكل من مصفوفة numpy وtensor الخاص بـ pytorch، النطاق المتوقع للقيم هو بين `[0, 1]` إذا كان tensor أو قائمة من tensors، فيجب أن يكون الشكل المتوقع `(B, C, H, W)` أو `(C, H, W)`. أما إذا كانت مصفوفة numpy أو قائمة من المصفوفات، فيجب أن يكون الشكل المتوقع `(B, H, W, C)` أو `(H, W, C)`.

num_inference_steps (`int`، *اختياري*، القيمة الافتراضية 50) : عدد خطوات إزالة الضوضاء. تؤدي زيادة عدد خطوات إزالة الضوضاء عادةً إلى صورة ذات جودة أعلى على حساب بطء الاستدلال.

sigmas (`list[float]`، *اختياري*) : قيم `sigmas` مخصصة لاستخدامها في عملية إزالة الضوضاء مع المجدولين الذين يدعمون معامل `sigmas` في طريقة `set_timesteps` الخاصة بهم. إذا لم تُعرَّف، فسيتم استخدام السلوك الافتراضي عند تمرير `num_inference_steps`.

guidance_scale (`float`، *اختياري*، القيمة الافتراضية 30.0) : مقياس التوجيه كما هو مُعرَّف في [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). يُعرَّف `guidance_scale` على أنه `w` من المعادلة 2. في [Imagen Paper](https://huggingface.co/papers/2205.11487). يتم تفعيل مقياس التوجيه عن طريق تعيين `guidance_scale > 1`. يشجع مقياس التوجيه الأعلى على توليد صور مرتبطة ارتباطًا وثيقًا بنص `prompt`، وعادةً على حساب انخفاض جودة الصورة.

num_images_per_prompt (`int`، *اختياري*، القيمة الافتراضية 1) : عدد الصور التي سيتم توليدها لكل موجه.

generator (`torch.Generator` أو `list[torch.Generator]`، *اختياري*) : مولّد واحد أو قائمة من [مولّدات torch](https://pytorch.org/docs/stable/generated/torch.Generator.html) لجعل التوليد حتميًا.

latents (`torch.FloatTensor`، *اختياري*) : كامنات ضجيج مُولّدة مسبقًا، مُستخرجة من توزيع غاوسي، تُستخدم كمدخلات لتوليد الصور. يمكن استخدامها لتعديل نفس التوليد باستخدام أوامر مختلفة. إذا لم تُقدَّم، فسيتم إنشاء كامنات من خلال الاستخراج باستخدام `generator` العشوائي المُقدَّم.

prompt_embeds (`torch.FloatTensor`، *اختياري*) : تمثيلات نصية مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، *مثلًا* وزن الأوامر. إذا لم تُقدَّم، فسيتم توليد تمثيلات النص من معامل الإدخال `prompt`.

pooled_prompt_embeds (`torch.FloatTensor`، *اختياري*) : تمثيلات نصية مجمّعة مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، *مثلًا* وزن الأوامر. إذا لم تُقدَّم، فسيتم توليد التمثيلات النصية المجمّعة من معامل الإدخال `prompt`.

output_type (`str`، *اختياري*، القيمة الافتراضية `"pil"`) : صيغة الصورة الناتجة عن عملية التوليد. اختر بين `"pil"` ([PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image`) أو `"np"` (`np.array`) أو `"pt"` (`torch.Tensor`).

return_dict (`bool`، *اختياري*، الافتراضي `True`) : ما إذا كان يجب إرجاع `~pipelines.flux.FluxPipelineOutput` بدلاً من tuple عادي.

joint_attention_kwargs (`dict`، *اختياري*) : قاموس kwargs يُمرَّر إلى `AttentionProcessor` إذا تم تحديده، كما هو معرَّف تحت `self.processor` في [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

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`، *اختياري*) : قائمة مدخلات المصفوفات (tensors) لدالة `callback_on_step_end`. سيتم تمرير المصفوفات المحددة في القائمة كحجة `callback_kwargs`. لن تتمكن من تضمين سوى المتغيرات المدرجة في خاصية `._callback_tensor_inputs` لفئة خط الأنابيب (pipeline) الخاص بك.

max_sequence_length (`int` الافتراضي 512) : أقصى طول تسلسل يُستخدم مع `prompt`.

**يعيد:** `~pipelines.flux.FluxPipelineOutput` أو `tuple`

`~pipelines.flux.FluxPipelineOutput` إذا كان `return_dict` هو True، وإلا `tuple`. عند إرجاع tuple، يكون العنصر الأول قائمة تحتوي على الصور المولّدة.

الدالة التي تُستدعى عند استدعاء خط أنابيب VisualCloze للتوليد.

أمثلة:
```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)
```

[المصدر](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py#L292)

**المعاملات:**

layout_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر التي تُعرّف عدد الأمثلة داخل السياق وعدد الصور المشاركة في المهمة.

task_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر لتحديد نية المهمة.

content_prompt (`str` أو `list[str]`، *اختياري*) : الأمر أو الأوامر لتحديد محتوى الصورة المستهدفة أو وصفها الذي سيتم توليده.

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 محمَّلة.

