Compel

2.3.1 · active · verified Thu Apr 16

Compel is an active Python library, currently at version 2.3.1, designed to enhance prompting for transformers-type text embedding systems. It provides a flexible and intuitive syntax for sophisticated prompt weighting, blending, and concatenation, commonly used with Hugging Face `diffusers` pipelines. The library aims to give users granular control over how text encoders interpret complex prompt strings, and it maintains a regular release cadence with ongoing development.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `CompelForSDXL` with a Hugging Face `diffusers` pipeline to apply weighting to both positive and negative prompts. It showcases the `++` and explicit number weighting syntax, and how to retrieve and pass the generated conditioning tensors (embeds and pooled_embeds) to the SDXL pipeline for image generation. Ensure you have `diffusers` and `torch` installed and a suitable Hugging Face model loaded.

import torch
from diffusers import DiffusionPipeline
from compel import CompelForSDXL

# Ensure you have a Hugging Face token if the model is private or gated
# os.environ['HF_TOKEN'] = os.environ.get('HF_TOKEN', '')

# Load an SDXL pipeline
pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    variant="fp16",
    use_safetensors=True,
    torch_dtype=torch.float16
).to("cuda") # Or 'cpu' if no GPU

# Initialize CompelForSDXL with the pipeline
compel = CompelForSDXL(pipeline)

# Define prompts with weighting syntax
positive_prompt = "A cat playing with a ball++ in the forest, (high quality, photorealistic)1.2"
negative_prompt = "deformed, ugly, blurry, out of focus, worst quality, low quality-"

# Generate conditioning tensors
conditioning = compel(positive_prompt)
negative_conditioning = compel(negative_prompt)

# For SDXL, prompt_embeds and pooled_prompt_embeds are used
image = pipeline(
    prompt_embeds=conditioning.embeds,
    pooled_prompt_embeds=conditioning.pooled_embeds,
    negative_prompt_embeds=negative_conditioning.embeds,
    negative_pooled_prompt_embeds=negative_conditioning.pooled_embeds,
    num_inference_steps=30,
    width=1024,
    height=1024
).images[0]

# Save the generated image
# image.save("compel_example_image.png")
print("Image generated successfully.")

view raw JSON →