Certainly! You can create a Gradio interface similar to your previous IP Adapter example, but using the PuLID pipeline instead. Below is an example of how you can set up a Gradio app with the PuLID pipeline.
Step 1: Import necessary modules and define the PuLIDPipeline class
Make sure you have all the required modules installed and import them. Then, include the PuLIDPipeline class (as provided in your code).
import gc
import cv2
import torch
import torch.nn as nn
import gradio as gr
import numpy as np
import random
from diffusers import (
DPMSolverMultistepScheduler,
StableDiffusionXLPipeline,
UNet2DConditionModel,
)
from facexlib.parsing import init_parsing_model
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
from huggingface_hub import hf_hub_download, snapshot_download
from insightface.app import FaceAnalysis
from safetensors.torch import load_file
from torchvision.transforms import InterpolationMode
from torchvision.transforms.functional import normalize, resize
from eva_clip import create_model_and_transforms
from eva_clip.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
from pulid.encoders import IDEncoder
from pulid.utils import img2tensor, is_torch2_available, tensor2img
if is_torch2_available():
from pulid.attention_processor import AttnProcessor2_0 as AttnProcessor
from pulid.attention_processor import IDAttnProcessor2_0 as IDAttnProcessor
else:
from pulid.attention_processor import AttnProcessor, IDAttnProcessor
import gradio as gr
# Define the PuLIDPipeline class (as provided in your code)
class PuLIDPipeline:
def __init__(self, *args, **kwargs):
super().__init__()
self.device = 'cuda'
sdxl_base_repo = 'stabilityai/stable-diffusion-xl-base-1.0'
sdxl_lightning_repo = 'ByteDance/SDXL-Lightning'
self.sdxl_base_repo = sdxl_base_repo
# Load base model
unet = UNet2DConditionModel.from_config(sdxl_base_repo, subfolder='unet').to(self.device, torch.float16)
unet.load_state_dict(
load_file(
hf_hub_download(sdxl_lightning_repo, 'sdxl_lightning_4step_unet.safetensors'), device=self.device
)
)
self.hack_unet_attn_layers(unet)
self.pipe = StableDiffusionXLPipeline.from_pretrained(
sdxl_base_repo, unet=unet, torch_dtype=torch.float16, variant="fp16"
).to(self.device)
self.pipe.watermark = None
# Scheduler
self.pipe.scheduler = DPMSolverMultistepScheduler.from_config(
self.pipe.scheduler.config, timestep_spacing="trailing"
)
# ID adapters
self.id_adapter = IDEncoder().to(self.device)
# Preprocessors
# Face align and parsing
self.face_helper = FaceRestoreHelper(
upscale_factor=1,
face_size=512,
crop_ratio=(1, 1),
det_model='retinaface_resnet50',
save_ext='png',
device=self.device,
)
self.face_helper.face_parse = None
self.face_helper.face_parse = init_parsing_model(model_name='bisenet', device=self.device)
# Clip-vit backbone
model, _, _ = create_model_and_transforms('EVA02-CLIP-L-14-336', 'eva_clip', force_custom_clip=True)
model = model.visual
self.clip_vision_model = model.to(self.device)
eva_transform_mean = getattr(self.clip_vision_model, 'image_mean', OPENAI_DATASET_MEAN)
eva_transform_std = getattr(self.clip_vision_model, 'image_std', OPENAI_DATASET_STD)
if not isinstance(eva_transform_mean, (list, tuple)):
eva_transform_mean = (eva_transform_mean,) * 3
if not isinstance(eva_transform_std, (list, tuple)):
eva_transform_std = (eva_transform_std,) * 3
self.eva_transform_mean = eva_transform_mean
self.eva_transform_std = eva_transform_std
# Antelopev2
snapshot_download('DIAMONIK7777/antelopev2', local_dir='models/antelopev2')
self.app = FaceAnalysis(
name='antelopev2', root='.', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']
)
self.app.prepare(ctx_id=0, det_size=(640, 640))
self.handler_ante = insightface.model_zoo.get_model('models/antelopev2/glintr100.onnx')
self.handler_ante.prepare(ctx_id=0)
gc.collect()
torch.cuda.empty_cache()
self.load_pretrain()
# Other configs
self.debug_img_list = []
def hack_unet_attn_layers(self, unet):
id_adapter_attn_procs = {}
for name, _ in unet.attn_processors.items():
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
if name.startswith("mid_block"):
hidden_size = unet.config.block_out_channels[-1]
elif name.startswith("up_blocks"):
block_id = int(name[len("up_blocks.")])
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
elif name.startswith("down_blocks"):
block_id = int(name[len("down_blocks.")])
hidden_size = unet.config.block_out_channels[block_id]
if cross_attention_dim is not None:
id_adapter_attn_procs[name] = IDAttnProcessor(
hidden_size=hidden_size,
cross_attention_dim=cross_attention_dim,
).to(unet.device)
else:
id_adapter_attn_procs[name] = AttnProcessor()
unet.set_attn_processor(id_adapter_attn_procs)
self.id_adapter_attn_layers = nn.ModuleList(unet.attn_processors.values())
def load_pretrain(self):
hf_hub_download('guozinan/PuLID', 'pulid_v1.bin', local_dir='models')
ckpt_path = 'models/pulid_v1.bin'
state_dict = torch.load(ckpt_path, map_location='cpu')
state_dict_dict = {}
for k, v in state_dict.items():
module = k.split('.')[0]
state_dict_dict.setdefault(module, {})
new_k = k[len(module) + 1 :]
state_dict_dict[module][new_k] = v
for module in state_dict_dict:
print(f'loading from {module}')
getattr(self, module).load_state_dict(state_dict_dict[module], strict=True)
def to_gray(self, img):
x = 0.299 * img[:, 0:1] + 0.587 * img[:, 1:2] + 0.114 * img[:, 2:3]
x = x.repeat(1, 3, 1, 1)
return x
def get_id_embedding(self, image):
"""
Args:
image: numpy rgb image, range [0, 255]
"""
self.face_helper.clean_all()
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Get antelopev2 embedding
face_info = self.app.get(image_bgr)
if len(face_info) > 0:
face_info = sorted(face_info, key=lambda x: (x['bbox'][2] - x['bbox'][0]) * (x['bbox'][3] - x['bbox'][1]))[
-1
] # only use the maximum face
id_ante_embedding = face_info['embedding']
self.debug_img_list.append(
image[
int(face_info['bbox'][1]) : int(face_info['bbox'][3]),
int(face_info['bbox'][0]) : int(face_info['bbox'][2]),
]
)
else:
id_ante_embedding = None
# Using facexlib to detect and align face
self.face_helper.read_image(image_bgr)
self.face_helper.get_face_landmarks_5(only_center_face=True)
self.face_helper.align_warp_face()
if len(self.face_helper.cropped_faces) == 0:
raise RuntimeError('Facial alignment failed.')
align_face = self.face_helper.cropped_faces[0]
# In case insightface didn't detect face
if id_ante_embedding is None:
print('Face detection failed with insightface, extracting embedding from aligned face.')
id_ante_embedding = self.handler_ante.get_feat(align_face)
id_ante_embedding = torch.from_numpy(id_ante_embedding).to(self.device)
if id_ante_embedding.ndim == 1:
id_ante_embedding = id_ante_embedding.unsqueeze(0)
# Parsing
input = img2tensor(align_face, bgr2rgb=True).unsqueeze(0) / 255.0
input = input.to(self.device)
parsing_out = self.face_helper.face_parse(normalize(input, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))[0]
parsing_out = parsing_out.argmax(dim=1, keepdim=True)
bg_label = [0, 16, 18, 7, 8, 9, 14, 15]
bg = sum(parsing_out == i for i in bg_label).bool()
white_image = torch.ones_like(input)
# Only keep the face features
face_features_image = torch.where(bg, white_image, self.to_gray(input))
self.debug_img_list.append(tensor2img(face_features_image, rgb2bgr=False))
# Transform img before sending to EVA-CLIP-ViT
face_features_image = resize(face_features_image, self.clip_vision_model.image_size, InterpolationMode.BICUBIC)
face_features_image = normalize(face_features_image, self.eva_transform_mean, self.eva_transform_std)
id_cond_vit, id_vit_hidden = self.clip_vision_model(
face_features_image, return_all_features=False, return_hidden=True, shuffle=False
)
id_cond_vit_norm = torch.norm(id_cond_vit, 2, 1, True)
id_cond_vit = torch.div(id_cond_vit, id_cond_vit_norm)
id_cond = torch.cat([id_ante_embedding, id_cond_vit], dim=-1)
id_uncond = torch.zeros_like(id_cond)
id_vit_hidden_uncond = []
for layer_idx in range(0, len(id_vit_hidden)):
id_vit_hidden_uncond.append(torch.zeros_like(id_vit_hidden[layer_idx]))
id_embedding = self.id_adapter(id_cond, id_vit_hidden)
uncond_id_embedding = self.id_adapter(id_uncond, id_vit_hidden_uncond)
# Return id_embedding
return torch.cat((uncond_id_embedding, id_embedding), dim=0)
def inference(self, prompt, size, prompt_n='', image_embedding=None, id_scale=1.0, guidance_scale=1.2, steps=4, generator=None):
images = self.pipe(
prompt=prompt,
negative_prompt=prompt_n,
num_images_per_prompt=size[0],
height=size[1],
width=size[2],
num_inference_steps=steps,
guidance_scale=guidance_scale,
cross_attention_kwargs={'id_embedding': image_embedding, 'id_scale': id_scale},
generator=generator,
).images
return images
Step 2: Instantiate the PuLID pipeline and define the inference function
We create an instance of the PuLIDPipeline and define an inference function that will be used by Gradio.
# Instantiate the PuLID pipeline
pipe = PuLIDPipeline()
# Maximum seed value
MAX_SEED = np.iinfo(np.int32).max
def infer_pulid(prompt, image, negative_prompt, seed, randomize_seed, guidance_scale, num_inference_steps, id_scale):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
else:
seed = int(seed)
generator = torch.Generator(device="cuda").manual_seed(seed)
# Convert PIL image to numpy array
if image is not None:
np_image = np.array(image)
# Ensure it's in RGB format
np_image = cv2.cvtColor(np_image, cv2.COLOR_RGB2BGR)
# Get id_embedding
image_embedding = pipe.get_id_embedding(np_image)
else:
image_embedding = None
# Generate images
images = pipe.inference(
prompt=prompt,
size=(1, 1024, 1024),
prompt_n=negative_prompt,
image_embedding=image_embedding,
id_scale=id_scale,
guidance_scale=guidance_scale,
steps=int(num_inference_steps),
generator=generator
)
return images, seed
Step 3: Set up the Gradio interface
Below is an example of how you can set up the Gradio Blocks interface.
# Now set up the Gradio interface
css = """
#col-container {
max-width: 800px;
margin-left: auto;
margin-right: auto;
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown("<h1 style='text-align: center;'>PuLID Image Generation</h1>")
with gr.Column(elem_id="col-container"):
with gr.Row():
with gr.Column():
prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt", lines=2)
negative_prompt = gr.Textbox(
label="Negative Prompt",
placeholder="Enter negative prompt",
value="nsfw, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality"
)
image = gr.Image(label="Input Image (for ID embedding)", type="pil")
with gr.Row():
seed = gr.Number(label="Seed", value=0, precision=0)
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
with gr.Accordion("Advanced Options", open=False):
guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=20.0, step=0.1, value=7.5)
num_inference_steps = gr.Slider(label="Number of Inference Steps", minimum=1, maximum=50, step=1, value=20)
id_scale = gr.Slider(label="ID Scale", minimum=0.0, maximum=2.0, step=0.1, value=1.0)
generate_button = gr.Button("Generate")
with gr.Column():
result_gallery = gr.Gallery(label="Generated Images").style(grid=[1], height='auto')
seed_used = gr.Number(label="Seed Used")
# Set up the button click event
generate_button.click(
fn=infer_pulid,
inputs=[prompt, image, negative_prompt, seed, randomize_seed, guidance_scale, num_inference_steps, id_scale],
outputs=[result_gallery, seed_used]
)
demo.launch()
Notes:
- The
get_id_embedding method expects an image in BGR format (as per OpenCV), so we ensure we convert the PIL image to a NumPy array and then to BGR format.
- The
size parameter in the inference method is set to generate images of size 1024x1024. You can adjust this if needed.
- The
seed management allows for reproducibility. When randomize_seed is False, it uses the seed provided by the user.
- Adjust the default values for parameters like
guidance_scale and id_scale based on what gives the best results with the PuLID pipeline.
Step 4: Run the app
When you run the script, it will start the Gradio app, and you can interact with it through your web browser.
This setup creates a Gradio interface where users can input a prompt, an image to guide the ID embedding, adjust parameters like guidance scale and number of inference steps, and generate images using the PuLID pipeline.
Remember to ensure that all dependencies are installed and that you have access to the required models and resources. Also, make sure that your environment has a CUDA-compatible GPU, as the pipeline uses CUDA for computations.