KseniaAI commited on
Commit
3cdac50
β€’
1 Parent(s): 1e49dc6

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +8 -6
  2. app.py +137 -0
  3. requirements.txt +10 -0
README.md CHANGED
@@ -1,12 +1,14 @@
1
  ---
2
- title: TestIPadapter
3
- emoji: πŸ“‰
4
- colorFrom: red
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 5.4.0
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: IP-Adapter-FaceID
3
+ emoji: πŸ§‘πŸΏπŸ§‘πŸ½β€πŸ¦±
4
+ colorFrom: gray
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 4.36.1
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
+ disable_embedding: true
12
  ---
13
 
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import spaces
3
+ from diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKL
4
+ from transformers import AutoFeatureExtractor
5
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
6
+ from ip_adapter.ip_adapter_faceid import IPAdapterFaceID, IPAdapterFaceIDPlus
7
+ from huggingface_hub import hf_hub_download
8
+ from insightface.app import FaceAnalysis
9
+ from insightface.utils import face_align
10
+ import gradio as gr
11
+ import cv2
12
+
13
+ base_model_path = "SG161222/Realistic_Vision_V4.0_noVAE"
14
+ vae_model_path = "stabilityai/sd-vae-ft-mse"
15
+ image_encoder_path = "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
16
+ ip_ckpt = hf_hub_download(repo_id="h94/IP-Adapter-FaceID", filename="ip-adapter-faceid_sd15.bin", repo_type="model")
17
+ ip_plus_ckpt = hf_hub_download(repo_id="h94/IP-Adapter-FaceID", filename="ip-adapter-faceid-plusv2_sd15.bin", repo_type="model")
18
+
19
+ safety_model_id = "CompVis/stable-diffusion-safety-checker"
20
+ safety_feature_extractor = AutoFeatureExtractor.from_pretrained(safety_model_id)
21
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(safety_model_id)
22
+
23
+ device = "cuda"
24
+
25
+ noise_scheduler = DDIMScheduler(
26
+ num_train_timesteps=1000,
27
+ beta_start=0.00085,
28
+ beta_end=0.012,
29
+ beta_schedule="scaled_linear",
30
+ clip_sample=False,
31
+ set_alpha_to_one=False,
32
+ steps_offset=1,
33
+ )
34
+ vae = AutoencoderKL.from_pretrained(vae_model_path).to(dtype=torch.float16)
35
+ pipe = StableDiffusionPipeline.from_pretrained(
36
+ base_model_path,
37
+ torch_dtype=torch.float16,
38
+ scheduler=noise_scheduler,
39
+ vae=vae,
40
+ feature_extractor=safety_feature_extractor,
41
+ safety_checker=safety_checker
42
+ ).to(device)
43
+
44
+ #pipe.load_lora_weights("h94/IP-Adapter-FaceID", weight_name="ip-adapter-faceid-plusv2_sd15_lora.safetensors")
45
+ #pipe.fuse_lora()
46
+
47
+ ip_model = IPAdapterFaceID(pipe, ip_ckpt, device)
48
+ ip_model_plus = IPAdapterFaceIDPlus(pipe, image_encoder_path, ip_plus_ckpt, device)
49
+
50
+ app = FaceAnalysis(name="buffalo_l", providers=['CPUExecutionProvider'])
51
+ app.prepare(ctx_id=0, det_size=(640, 640))
52
+
53
+ cv2.setNumThreads(1)
54
+
55
+ @spaces.GPU(enable_queue=True)
56
+ def generate_image(images, prompt, negative_prompt, preserve_face_structure, face_strength, likeness_strength, nfaa_negative_prompt, progress=gr.Progress(track_tqdm=True)):
57
+ faceid_all_embeds = []
58
+ first_iteration = True
59
+ for image in images:
60
+ face = cv2.imread(image)
61
+ faces = app.get(face)
62
+ faceid_embed = torch.from_numpy(faces[0].normed_embedding).unsqueeze(0)
63
+ faceid_all_embeds.append(faceid_embed)
64
+ if(first_iteration and preserve_face_structure):
65
+ face_image = face_align.norm_crop(face, landmark=faces[0].kps, image_size=224) # you can also segment the face
66
+ first_iteration = False
67
+
68
+ average_embedding = torch.mean(torch.stack(faceid_all_embeds, dim=0), dim=0)
69
+
70
+ total_negative_prompt = f"{negative_prompt} {nfaa_negative_prompt}"
71
+
72
+ if(not preserve_face_structure):
73
+ print("Generating normal")
74
+ image = ip_model.generate(
75
+ prompt=prompt, negative_prompt=total_negative_prompt, faceid_embeds=average_embedding,
76
+ scale=likeness_strength, width=512, height=512, num_inference_steps=30
77
+ )
78
+ else:
79
+ print("Generating plus")
80
+ image = ip_model_plus.generate(
81
+ prompt=prompt, negative_prompt=total_negative_prompt, faceid_embeds=average_embedding,
82
+ scale=likeness_strength, face_image=face_image, shortcut=True, s_scale=face_strength, width=512, height=512, num_inference_steps=30
83
+ )
84
+ print(image)
85
+ return image
86
+
87
+ def change_style(style):
88
+ if style == "Photorealistic":
89
+ return(gr.update(value=True), gr.update(value=1.3), gr.update(value=1.0))
90
+ else:
91
+ return(gr.update(value=True), gr.update(value=0.1), gr.update(value=0.8))
92
+
93
+ def swap_to_gallery(images):
94
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
95
+
96
+ def remove_back_to_files():
97
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
98
+ css = '''
99
+ h1{margin-bottom: 0 !important}
100
+ '''
101
+ with gr.Blocks(css=css) as demo:
102
+ gr.Markdown("# IP-Adapter-FaceID Plus demo")
103
+ gr.Markdown("Demo for the [h94/IP-Adapter-FaceID model](https://huggingface.co/h94/IP-Adapter-FaceID) - Generate AI images with your own face - Non-commercial license")
104
+ with gr.Row():
105
+ with gr.Column():
106
+ files = gr.Files(
107
+ label="Drag 1 or more photos of your face",
108
+ file_types=["image"]
109
+ )
110
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=125)
111
+ with gr.Column(visible=False) as clear_button:
112
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
113
+ prompt = gr.Textbox(label="Prompt",
114
+ info="Try something like 'a photo of a man/woman/person'",
115
+ placeholder="A photo of a [man/woman/person]...")
116
+ negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="low quality")
117
+ style = gr.Radio(label="Generation type", info="For stylized try prompts like 'a watercolor painting of a woman'", choices=["Photorealistic", "Stylized"], value="Photorealistic")
118
+ submit = gr.Button("Submit")
119
+ with gr.Accordion(open=False, label="Advanced Options"):
120
+ 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)
121
+ 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)
122
+ likeness_strength = gr.Slider(label="Face Embed strength", value=1.0, step=0.1, minimum=0, maximum=5)
123
+ nfaa_negative_prompts = gr.Textbox(label="Appended Negative Prompts", info="Negative prompts to steer generations towards safe for all audiences outputs", value="naked, bikini, skimpy, scanty, bare skin, lingerie, swimsuit, exposed, see-through")
124
+ with gr.Column():
125
+ gallery = gr.Gallery(label="Generated Images")
126
+ style.change(fn=change_style,
127
+ inputs=style,
128
+ outputs=[preserve, face_strength, likeness_strength])
129
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
130
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
131
+ submit.click(fn=generate_image,
132
+ inputs=[files,prompt,negative_prompt,preserve, face_strength, likeness_strength, nfaa_negative_prompts],
133
+ outputs=gallery)
134
+
135
+ gr.Markdown("This demo includes extra features to mitigate the implicit bias of the model and prevent explicit usage of it to generate content with faces of people, including third parties, that is not safe for all audiences, including naked or semi-naked people.")
136
+
137
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ insightface==0.7.3
2
+ diffusers==0.25.0
3
+ transformers
4
+ accelerate
5
+ safetensors
6
+ einops
7
+ onnxruntime-gpu
8
+ spaces==0.19.4
9
+ opencv-python
10
+ git+https://github.com/tencent-ailab/IP-Adapter.git