|
import io |
|
|
|
import torch |
|
from PIL import Image |
|
import struct |
|
import numpy as np |
|
from comfy.cli_args import args, LatentPreviewMethod |
|
from comfy.taesd.taesd import TAESD |
|
import comfy.model_management |
|
import folder_paths |
|
import comfy.utils |
|
import logging |
|
|
|
MAX_PREVIEW_RESOLUTION = args.preview_size |
|
|
|
def preview_to_image(latent_image): |
|
latents_ubyte = (((latent_image + 1.0) / 2.0).clamp(0, 1) |
|
.mul(0xFF) |
|
).to(device="cpu", dtype=torch.uint8, non_blocking=comfy.model_management.device_supports_non_blocking(latent_image.device)) |
|
|
|
return Image.fromarray(latents_ubyte.numpy()) |
|
|
|
class LatentPreviewer: |
|
def decode_latent_to_preview(self, x0): |
|
pass |
|
|
|
def decode_latent_to_preview_image(self, preview_format, x0): |
|
preview_image = self.decode_latent_to_preview(x0) |
|
return ("GIF", preview_image, MAX_PREVIEW_RESOLUTION) |
|
|
|
class Latent2RGBPreviewer(LatentPreviewer): |
|
def __init__(self): |
|
|
|
|
|
latent_rgb_factors =[ |
|
[-0.0069, -0.0045, 0.0018], |
|
[ 0.0154, -0.0692, -0.0274], |
|
[ 0.0333, 0.0019, 0.0206], |
|
[-0.1390, 0.0628, 0.1678], |
|
[-0.0725, 0.0134, -0.1898], |
|
[ 0.0074, -0.0270, -0.0209], |
|
[-0.0176, -0.0277, -0.0221], |
|
[ 0.5294, 0.5204, 0.3852], |
|
[-0.0326, -0.0446, -0.0143], |
|
[-0.0659, 0.0153, -0.0153], |
|
[ 0.0185, -0.0217, 0.0014], |
|
[-0.0396, -0.0495, -0.0281] |
|
] |
|
self.latent_rgb_factors = torch.tensor(latent_rgb_factors, device="cpu").transpose(0, 1) |
|
self.latent_rgb_factors_bias = [-0.0940, -0.1418, -0.1453] |
|
|
|
def decode_latent_to_preview(self, x0): |
|
self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device) |
|
if self.latent_rgb_factors_bias is not None: |
|
self.latent_rgb_factors_bias = torch.tensor(self.latent_rgb_factors_bias, device="cpu").to(dtype=x0.dtype, device=x0.device) |
|
|
|
latent_image = torch.nn.functional.linear(x0[0].permute(1, 2, 0), self.latent_rgb_factors, |
|
bias=self.latent_rgb_factors_bias) |
|
return preview_to_image(latent_image) |
|
|
|
|
|
def get_previewer(): |
|
previewer = None |
|
method = args.preview_method |
|
if method != LatentPreviewMethod.NoPreviews: |
|
|
|
|
|
if method == LatentPreviewMethod.Auto: |
|
method = LatentPreviewMethod.Latent2RGB |
|
|
|
if previewer is None: |
|
previewer = Latent2RGBPreviewer() |
|
return previewer |
|
|
|
def prepare_callback(model, steps, x0_output_dict=None): |
|
preview_format = "JPEG" |
|
if preview_format not in ["JPEG", "PNG"]: |
|
preview_format = "JPEG" |
|
|
|
previewer = get_previewer() |
|
|
|
pbar = comfy.utils.ProgressBar(steps) |
|
def callback(step, x0, x, total_steps): |
|
if x0_output_dict is not None: |
|
x0_output_dict["x0"] = x0 |
|
preview_bytes = None |
|
if previewer: |
|
preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0) |
|
pbar.update_absolute(step + 1, total_steps, preview_bytes) |
|
return callback |
|
|
|
|