"""Prompt-to-image pipeline: loading, sampling, decoding and PNG metadata.""" from __future__ import annotations import json from collections.abc import Sequence from dataclasses import asdict, dataclass, field from enum import Enum from pathlib import Path import torch from huggingface_hub import snapshot_download from PIL import Image, PngImagePlugin from torch import Tensor from .configuration import read_inference_policy from .inference import ( DFlowEngine, GenerationSettings, ImageToImage, LatentCallback, ) from .loading import ( CONFIG_FILENAME, load_dflow_denoiser, load_text_adapter_tensors, read_release_version, ) from .preview import preview_images from .text_conditioning import DFlowTextEncoder, TextAdapter from .vae import DFlowVae from .version import __version__ REPOSITORY = "data-archetype/dflow_2b" TEXT_ENCODER_DIRNAME = "text_encoder" PNG_METADATA_KEY = "dflow" _RELEASE_PATTERNS = ( "model.safetensors", "config.json", "release.json", f"{TEXT_ENCODER_DIRNAME}/*", ) def resolve_release_directory( path_or_repository: str | Path, *, revision: str | None, cache_dir: Path | None, ) -> Path: """Return a local release directory. A ``Path`` or an existing directory is used as it is; any other string with a ``/`` is a Hub repository id whose weights and text encoder are downloaded at ``revision``. Raises: FileNotFoundError: If a ``Path`` names no directory, or a string is neither a directory nor a Hub id. ValueError: If ``revision`` is given with a local directory. """ if isinstance(path_or_repository, Path): if not path_or_repository.is_dir(): raise FileNotFoundError(f"No release directory at {path_or_repository}.") return _local_release(path_or_repository, revision) local = Path(path_or_repository).expanduser() if local.is_dir(): return _local_release(local, revision) if "/" not in path_or_repository: raise FileNotFoundError( f"No release folder {path_or_repository!r} here; pass its path or the " "Hub id data-archetype/dflow_2b." ) return Path( snapshot_download( path_or_repository, revision=revision, allow_patterns=list(_RELEASE_PATTERNS), cache_dir=None if cache_dir is None else str(cache_dir), ) ) def _local_release(directory: Path, revision: str | None) -> Path: """Return a local release directory, which has no Hub revision. Raises: ValueError: If ``revision`` is given. """ if revision is not None: raise ValueError( f"Revision {revision!r} selects a Hub release, but {directory} is a " "local folder. Load the repository id data-archetype/dflow_2b (the " "DFlow Loader's hub source) to use a revision." ) return directory @dataclass(frozen=True) class DFlowComponents: """The loaded parts of the model. Attributes: engine: Denoiser and text encoder. vae: The dinac3_96 autoencoder. compiled: Whether the blocks were compiled. weights_version: The release the weights come from (``release.json``). """ engine: DFlowEngine vae: DFlowVae compiled: bool weights_version: str @classmethod def from_pretrained( cls, path_or_repository: str | Path = REPOSITORY, *, device: torch.device | str = "cuda", compile: bool = True, revision: str | None = None, cache_dir: Path | None = None, vae_dir: Path | None = None, ) -> DFlowComponents: """Load the denoiser, text encoder and autoencoder. Args: path_or_repository: A local release directory or Hub repository. device: CUDA device. compile: ``torch.compile`` the denoiser blocks, encoder layers and autoencoder. Graphs build on first use (30 to 45 seconds); False runs eagerly. revision: Hub revision of the release (a repository id only). cache_dir: Hugging Face cache directory, or None for the default. vae_dir: A local copy of ``data-archetype/dinac3_96``, or None to download its pinned commit. Raises: FileNotFoundError: If release files are missing. ValueError: On a non-CUDA device or a release that does not match this code. """ target = torch.device(device) directory = resolve_release_directory( path_or_repository, revision=revision, cache_dir=cache_dir ) model = load_dflow_denoiser(directory, device=target, compile_model=compile) adapter = TextAdapter() adapter.load_state_dict(load_text_adapter_tensors(directory), strict=True) text_encoder = DFlowTextEncoder.from_directory( directory / TEXT_ENCODER_DIRNAME, adapter=adapter, device=target ) if compile: text_encoder.compile_layers() vae = DFlowVae.from_pretrained( device=target, compile=compile, local_dir=vae_dir, cache_dir=cache_dir ) policy = read_inference_policy(directory / CONFIG_FILENAME) return cls( engine=DFlowEngine(model, text_encoder, policy=policy), vae=vae, compiled=compile, weights_version=read_release_version(directory), ) class OutputType(Enum): """What ``DFlowPipeline.__call__`` returns.""" PIL = "pil" TENSOR = "tensor" LATENT = "latent" @dataclass(frozen=True) class DFlowOutput: """Images of one call. Attributes: images: PIL images with their settings in the PNG text chunk (PIL output), else empty. tensors: ``[B, 3, H, W]`` float32 RGB in ``[-1, 1]`` (TENSOR output), or ``[B, 96, h, w]`` latents (LATENT output), else None. settings: The settings of the call. """ images: list[Image.Image] tensors: Tensor | None settings: GenerationSettings @dataclass class DFlowPipeline: """Text to image with dflow_2b. Example:: pipe = DFlowPipeline.from_pretrained("data-archetype/dflow_2b") image = pipe("A lighthouse on a cliff at dusk.").images[0] image.save("lighthouse.png", pnginfo=pipe.png_info(image)) """ components: DFlowComponents default_settings: GenerationSettings = field(default_factory=GenerationSettings) @classmethod def from_pretrained( cls, path_or_repository: str | Path = REPOSITORY, *, device: torch.device | str = "cuda", compile: bool = True, revision: str | None = None, cache_dir: Path | None = None, vae_dir: Path | None = None, ) -> DFlowPipeline: """Load a pipeline (see ``DFlowComponents.from_pretrained``).""" return cls( DFlowComponents.from_pretrained( path_or_repository, device=device, compile=compile, revision=revision, cache_dir=cache_dir, vae_dir=vae_dir, ) ) def __call__( self, prompt: str | Sequence[str], settings: GenerationSettings | None = None, *, num_images: int = 1, output_type: OutputType = OutputType.PIL, image_to_image: ImageToImage | None = None, callback: LatentCallback | None = None, ) -> DFlowOutput: """Generate images. Args: prompt: One prompt (repeated ``num_images`` times) or a list of prompts with the same token count. settings: Size, seed, sampling and guidance; the pipeline's ``default_settings`` when None. num_images: Images per prompt string (a single prompt only). output_type: PIL images, RGB tensors or latents. image_to_image: Start latents and start step, or None. callback: Receives the predicted clean latents after each update (``dflow.preview.LatentRgbPreview`` turns them into previews). Raises: ValueError: For ``num_images`` < 1 or with a prompt list. """ chosen = self.default_settings if settings is None else settings prompts = _prompt_list(prompt, num_images) latents = self.components.engine.sample( prompts, chosen, image_to_image=image_to_image, callback=callback ) match output_type: case OutputType.LATENT: return DFlowOutput(images=[], tensors=latents, settings=chosen) case OutputType.TENSOR: rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0) return DFlowOutput(images=[], tensors=rgb, settings=chosen) case OutputType.PIL: rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0) images = preview_images(rgb) for index, image in enumerate(images): image.info[PNG_METADATA_KEY] = generation_metadata( prompts[index], chosen, batch_index=index, weights_version=self.components.weights_version, ) return DFlowOutput(images=images, tensors=None, settings=chosen) case _ as unreachable: raise ValueError(f"Unsupported output type: {unreachable}") @staticmethod def png_info(image: Image.Image) -> PngImagePlugin.PngInfo: """A ``PngInfo`` carrying the image's generation metadata, for ``image.save(path, pnginfo=...)``. Raises: KeyError: If the image did not come from this pipeline. """ info = PngImagePlugin.PngInfo() info.add_text(PNG_METADATA_KEY, str(image.info[PNG_METADATA_KEY])) return info def generation_metadata( prompt: str, settings: GenerationSettings, *, batch_index: int, weights_version: str, ) -> str: """JSON text describing one generated image; ``model`` names the release of the weights, ``package`` the code's version.""" payload = { "model": f"dflow_2b {weights_version}", "package": __version__, "prompt": prompt, "batch_index": batch_index, "settings": asdict(settings), } return json.dumps(payload, default=_json_value, sort_keys=True) def _json_value(value: object) -> object: """JSON form of enums in the settings.""" match value: case Enum(): return value.value case _: raise TypeError(f"Cannot serialize {type(value).__name__} to JSON.") def _prompt_list(prompt: str | Sequence[str], num_images: int) -> list[str]: """The batch's prompts. Raises: ValueError: For ``num_images`` < 1, or ``num_images`` > 1 with a list. """ if num_images < 1: raise ValueError(f"num_images must be >= 1, got {num_images}.") if isinstance(prompt, str): return [prompt] * num_images if num_images != 1: raise ValueError("num_images applies to a single prompt string only.") return list(prompt)