Commit
•
019effa
1
Parent(s):
26fa961
Upload CLapptest.py
Browse filesto change model, but choosing output directory doesnt work
- CLapptest.py +157 -0
CLapptest.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import cuda
|
3 |
+
import spaces
|
4 |
+
from diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKL
|
5 |
+
from transformers import AutoFeatureExtractor
|
6 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
7 |
+
from ip_adapter.ip_adapter_faceid import IPAdapterFaceID, IPAdapterFaceIDPlus
|
8 |
+
from huggingface_hub import hf_hub_download
|
9 |
+
from insightface.app import FaceAnalysis
|
10 |
+
from insightface.utils import face_align
|
11 |
+
import gradio as gr
|
12 |
+
import cv2
|
13 |
+
import argparse
|
14 |
+
|
15 |
+
OUTPUT_DIR = None # replace with your output directory
|
16 |
+
|
17 |
+
# Initialize the argument parser
|
18 |
+
parser = argparse.ArgumentParser(description='Choose a model etc')
|
19 |
+
parser.add_argument('--model', type=str, default='Lykon/AbsoluteReality', help='choose model from huggingface')
|
20 |
+
parser.add_argument('--output_dir', type=str, default='/content/Ip-Adapter-FaceID/results', help='The directory to save the output.')
|
21 |
+
# Parse the arguments
|
22 |
+
args = parser.parse_args()
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
base_model_path = "Lykon/AbsoluteReality"
|
27 |
+
vae_model_path = "stabilityai/sd-vae-ft-mse"
|
28 |
+
image_encoder_path = "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
29 |
+
ip_ckpt = hf_hub_download(repo_id="h94/IP-Adapter-FaceID", filename="ip-adapter-faceid_sd15.bin", repo_type="model")
|
30 |
+
ip_plus_ckpt = hf_hub_download(repo_id="h94/IP-Adapter-FaceID", filename="ip-adapter-faceid-plusv2_sd15.bin", repo_type="model")
|
31 |
+
|
32 |
+
safety_model_id = None
|
33 |
+
safety_feature_extractor = None
|
34 |
+
safety_checker = None
|
35 |
+
|
36 |
+
device = "cuda"
|
37 |
+
|
38 |
+
noise_scheduler = DDIMScheduler(
|
39 |
+
num_train_timesteps=1000,
|
40 |
+
beta_start=0.00085,
|
41 |
+
beta_end=0.012,
|
42 |
+
beta_schedule="scaled_linear",
|
43 |
+
clip_sample=False,
|
44 |
+
set_alpha_to_one=False,
|
45 |
+
steps_offset=1,
|
46 |
+
)
|
47 |
+
vae = AutoencoderKL.from_pretrained(vae_model_path).to(dtype=torch.float16)
|
48 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
49 |
+
base_model_path,
|
50 |
+
torch_dtype=torch.float16,
|
51 |
+
scheduler=noise_scheduler,
|
52 |
+
vae=vae,
|
53 |
+
feature_extractor=safety_feature_extractor,
|
54 |
+
safety_checker=safety_checker
|
55 |
+
)
|
56 |
+
|
57 |
+
#pipe.load_lora_weights("h94/IP-Adapter-FaceID", weight_name="ip-adapter-faceid-plusv2_sd15_lora.safetensors")
|
58 |
+
#pipe.fuse_lora()
|
59 |
+
|
60 |
+
ip_model = IPAdapterFaceID(pipe, ip_ckpt, device)
|
61 |
+
ip_model_plus = IPAdapterFaceIDPlus(pipe, image_encoder_path, ip_plus_ckpt, device)
|
62 |
+
|
63 |
+
@spaces.GPU(enable_queue=True)
|
64 |
+
def generate_image(images, prompt, negative_prompt, preserve_face_structure, face_strength, likeness_strength, num_samples, guidance_scale, nfaa_negative_prompt, progress=gr.Progress(track_tqdm=True)):
|
65 |
+
print(cuda.memory_summary())
|
66 |
+
pipe.to(device)
|
67 |
+
app = FaceAnalysis(name="buffalo_l", providers=['CUDAExecutionProvider','CPUExecutionProvider'])
|
68 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
69 |
+
print(cuda.memory_summary())
|
70 |
+
faceid_all_embeds = []
|
71 |
+
first_iteration = True
|
72 |
+
for image in images:
|
73 |
+
face = cv2.imread(image)
|
74 |
+
faces = app.get(face)
|
75 |
+
faceid_embed = torch.from_numpy(faces[0].normed_embedding).unsqueeze(0)
|
76 |
+
faceid_all_embeds.append(faceid_embed)
|
77 |
+
if(first_iteration and preserve_face_structure):
|
78 |
+
face_image = face_align.norm_crop(face, landmark=faces[0].kps, image_size=224) # you can also segment the face
|
79 |
+
first_iteration = False
|
80 |
+
|
81 |
+
average_embedding = torch.mean(torch.stack(faceid_all_embeds, dim=0), dim=0)
|
82 |
+
|
83 |
+
total_negative_prompt = f"{negative_prompt} {nfaa_negative_prompt}"
|
84 |
+
|
85 |
+
if(not preserve_face_structure):
|
86 |
+
print("Generating normal")
|
87 |
+
image = ip_model.generate(
|
88 |
+
prompt=prompt, negative_prompt=total_negative_prompt, faceid_embeds=average_embedding,
|
89 |
+
scale=likeness_strength, width=512, height=512, num_inference_steps=30
|
90 |
+
)
|
91 |
+
else:
|
92 |
+
print("Generating plus")
|
93 |
+
image = ip_model_plus.generate(
|
94 |
+
prompt=prompt, negative_prompt=total_negative_prompt, faceid_embeds=average_embedding,
|
95 |
+
scale=likeness_strength, face_image=face_image, shortcut=True, s_scale=face_strength, num_samples=num_samples, guidance_scale=guidance_scale, width=512, height=512, num_inference_steps=30
|
96 |
+
)
|
97 |
+
|
98 |
+
print(cuda.memory_summary())
|
99 |
+
print(image)
|
100 |
+
return image
|
101 |
+
|
102 |
+
def change_style(style):
|
103 |
+
if style == "Photorealistic":
|
104 |
+
return(gr.update(value=True), gr.update(value=1.3), gr.update(value=1.0))
|
105 |
+
else:
|
106 |
+
return(gr.update(value=True), gr.update(value=0.1), gr.update(value=0.8))
|
107 |
+
|
108 |
+
def swap_to_gallery(images):
|
109 |
+
return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
|
110 |
+
|
111 |
+
def remove_back_to_files():
|
112 |
+
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
|
113 |
+
css = '''
|
114 |
+
h1{margin-bottom: 0 !important}
|
115 |
+
'''
|
116 |
+
with gr.Blocks(css=css) as demo:
|
117 |
+
gr.Markdown("# IP-Adapter-FaceID Plus demo")
|
118 |
+
gr.Markdown("Demo for the [h94/IP-Adapter-FaceID model](https://huggingface.co/h94/IP-Adapter-FaceID) - Non-commercial license")
|
119 |
+
with gr.Row():
|
120 |
+
with gr.Column():
|
121 |
+
files = gr.Files(
|
122 |
+
label="Drag 1 or more photos of your face",
|
123 |
+
file_types=["image"]
|
124 |
+
)
|
125 |
+
uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=125)
|
126 |
+
with gr.Column(visible=False) as clear_button:
|
127 |
+
remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
|
128 |
+
prompt = gr.Textbox(label="Prompt",
|
129 |
+
info="Try something like 'a photo of a man/woman/person'",
|
130 |
+
placeholder="A photo of a [man/woman/person]...")
|
131 |
+
negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality")
|
132 |
+
style = gr.Radio(label="Generation type", info="For stylized try prompts like 'a watercolor painting of a woman'", choices=["Photorealistic", "Stylized"], value="Photorealistic")
|
133 |
+
#submit = gr.Button("Submit")
|
134 |
+
with gr.Accordion(open=False, label="Advanced Options"):
|
135 |
+
preserve = gr.Checkbox(label="Preserve Face Structure", info="Higher quality, less versatility (the face structure of your first photo will be preserved). Unchecking this will use the v1 model.", value=True)
|
136 |
+
face_strength = gr.Slider(label="Face Structure strength", info="Only applied if preserve face structure is checked", value=1.3, step=0.1, minimum=0, maximum=3)
|
137 |
+
likeness_strength = gr.Slider(label="Face Embed strength", value=1.0, step=0.1, minimum=0, maximum=5)
|
138 |
+
#seed = gr.Slider(label="seed", value=1000, step=100, minimum=100, maximum=2000)
|
139 |
+
guidance_scale = gr.Slider(label="CFG", value=1.0, step=0.5, minimum=0, maximum=20)
|
140 |
+
num_samples = gr.Slider(label="samples", value=1, step=1, minimum=1, maximum=16)
|
141 |
+
nfaa_negative_prompts = gr.Textbox(label="Appended Negative Prompts 4 realistic vision model", info="Negative prompts to steer generations towards safe for all audiences outputs", value="deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, close up, cropped, out of frame, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck")
|
142 |
+
with gr.Column():
|
143 |
+
gallery = gr.Gallery(label="Generated Images")
|
144 |
+
submit = gr.Button("Submit")
|
145 |
+
style.change(fn=change_style,
|
146 |
+
inputs=style,
|
147 |
+
outputs=[preserve, face_strength, likeness_strength])
|
148 |
+
files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
|
149 |
+
remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
|
150 |
+
#submit = gr.Button("Submit")
|
151 |
+
submit.click(fn=generate_image,
|
152 |
+
inputs=[files,prompt,negative_prompt,preserve, face_strength, likeness_strength, num_samples, guidance_scale, nfaa_negative_prompts],
|
153 |
+
outputs=gallery)
|
154 |
+
|
155 |
+
gr.Markdown("safety filter is on")
|
156 |
+
print(cuda.memory_summary())
|
157 |
+
demo.launch(share=True)
|