tzhi-bytedance commited on
Commit
54c1f4b
·
verified ·
1 Parent(s): 628a6ae

Upload 41 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,33 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/pipeline.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/poses/p1_1.jpeg filter=lfs diff=lfs merge=lfs -text
38
+ assets/poses/p1_2.jpeg filter=lfs diff=lfs merge=lfs -text
39
+ assets/poses/p2.png filter=lfs diff=lfs merge=lfs -text
40
+ assets/poses/p3_1.jpeg filter=lfs diff=lfs merge=lfs -text
41
+ assets/poses/p3_2.jpeg filter=lfs diff=lfs merge=lfs -text
42
+ assets/poses/p4.jpeg filter=lfs diff=lfs merge=lfs -text
43
+ assets/poses/p5.jpeg filter=lfs diff=lfs merge=lfs -text
44
+ assets/poses/p6.jpeg filter=lfs diff=lfs merge=lfs -text
45
+ assets/subjects/man/0.jpg filter=lfs diff=lfs merge=lfs -text
46
+ assets/subjects/man/12.jpg filter=lfs diff=lfs merge=lfs -text
47
+ assets/subjects/man/13.jpg filter=lfs diff=lfs merge=lfs -text
48
+ assets/subjects/man/21.jpg filter=lfs diff=lfs merge=lfs -text
49
+ assets/subjects/man/27.jpg filter=lfs diff=lfs merge=lfs -text
50
+ assets/subjects/man/40.jpg filter=lfs diff=lfs merge=lfs -text
51
+ assets/subjects/man/43.jpg filter=lfs diff=lfs merge=lfs -text
52
+ assets/subjects/man/44.jpg filter=lfs diff=lfs merge=lfs -text
53
+ assets/subjects/man/49.jpg filter=lfs diff=lfs merge=lfs -text
54
+ assets/subjects/man/51.jpg filter=lfs diff=lfs merge=lfs -text
55
+ assets/subjects/man/52.jpg filter=lfs diff=lfs merge=lfs -text
56
+ assets/subjects/woman/0.jpg filter=lfs diff=lfs merge=lfs -text
57
+ assets/subjects/woman/16.jpg filter=lfs diff=lfs merge=lfs -text
58
+ assets/subjects/woman/26.jpg filter=lfs diff=lfs merge=lfs -text
59
+ assets/subjects/woman/35.jpg filter=lfs diff=lfs merge=lfs -text
60
+ assets/subjects/woman/38.jpg filter=lfs diff=lfs merge=lfs -text
61
+ assets/subjects/woman/53.jpg filter=lfs diff=lfs merge=lfs -text
62
+ assets/subjects/woman/59.jpg filter=lfs diff=lfs merge=lfs -text
63
+ assets/subjects/woman/66.jpg filter=lfs diff=lfs merge=lfs -text
64
+ assets/subjects/woman/99.jpg filter=lfs diff=lfs merge=lfs -text
65
+ assets/teaser.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,14 +1,18 @@
1
  ---
2
- title: ID Patch SDXL
3
- emoji: 👁
4
- colorFrom: yellow
5
  colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 5.27.1
8
  app_file: app.py
9
- pinned: false
10
  license: apache-2.0
11
  short_description: Robust ID Association for Group Photo Personalization.
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
1
  ---
2
+ title: ID-Patch
3
+ emoji: 📸
4
+ colorFrom: red
5
  colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 5.23.1
8
  app_file: app.py
9
+ pinned: true
10
  license: apache-2.0
11
  short_description: Robust ID Association for Group Photo Personalization.
12
  ---
13
 
14
+ The images used in this demo are sourced from consented subjects or generated by the models. These pictures are intended solely to show the capabilities of our research. If you have any concerns, please contact us, and we will promptly remove any inappropriate content.
15
+
16
+ The use of the released code, model, and demo must strictly adhere to the respective licenses. The code in this demo is licensed under the [Apache License 2.0](./LICENSE), and our model is released under the [Creative Commons Attribution-NonCommercial 4.0 International Public License](https://creativecommons.org/licenses/by-nc/4.0/legalcode) for academic research purposes only. Any manual or automatic downloading of the face models from [InsightFace](https://github.com/deepinsight/insightface), the [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) base model, LoRAs ([Realism](https://civitai.com/models/631986?modelVersionId=706528) and [Anti-blur](https://civitai.com/models/675581/anti-blur-flux-lora)), *etc.*, must follow their original licenses and be used only for academic research purposes.
17
+
18
+ This research aims to positively impact the field of Generative AI. Any usage of this method must be responsible and comply with local laws. The developers do not assume any responsibility for any potential misuse. We added the "AI Generated" watermark for enhanced safety.
app.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 Bytedance Ltd. and/or its affiliates. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import gradio as gr
17
+ import huggingface_hub
18
+ import pillow_avif
19
+ import spaces
20
+ import gc
21
+ from huggingface_hub import snapshot_download
22
+ from pillow_heif import register_heif_opener
23
+ from PIL import Image, ImageDraw, ImageFont
24
+
25
+ from pathlib import Path
26
+ import numpy as np
27
+ import cv2
28
+ import tensorflow as tf
29
+ from mtcnn import MTCNN
30
+ from insightface.utils import face_align
31
+ import facexlib
32
+ import torch
33
+ from modules.inferencer import IDPatchInferencer
34
+ from rtmlib import Body
35
+ from utils.draw_condition import draw_openpose_from_mmpose
36
+
37
+ # Register HEIF support for Pillow
38
+ register_heif_opener()
39
+
40
+ loaded_pipeline_config = {
41
+ 'pipeline': None,
42
+ 'face_encoder': None,
43
+ 'face_detector': None
44
+ }
45
+
46
+ body_estimator = Body(to_openpose=False, mode='balanced', backend='onnxruntime', device='cpu')
47
+
48
+ def pil_to_cv2(pil_image):
49
+ """PIL.Image -> OpenCV BGR Image"""
50
+ cv2_image = np.array(pil_image)
51
+ cv2_image = cv2.cvtColor(cv2_image, cv2.COLOR_RGB2BGR)
52
+ return cv2_image
53
+
54
+ def mtcnn_to_kps(mtcnn_results):
55
+ kps = np.array([mtcnn_results[0]['keypoints']['left_eye'], mtcnn_results[0]['keypoints']['right_eye'], mtcnn_results[0]['keypoints']['nose'], mtcnn_results[0]['keypoints']['mouth_left'], mtcnn_results[0]['keypoints']['mouth_right']])
56
+ return kps
57
+
58
+ def extract_face_emb(arcface_encoder, cropped_face):
59
+ device = "cuda" if torch.cuda.is_available() else "cpu"
60
+ face_image = torch.from_numpy(cropped_face).unsqueeze(0).permute(0,3,1,2) / 255.
61
+ face_image = 2 * face_image - 1
62
+ face_image = face_image.to(device).contiguous()
63
+ face_emb = arcface_encoder(face_image)[0]
64
+ return face_emb
65
+
66
+
67
+ def download_models():
68
+ snapshot_download(repo_id='ByteDance/ID-Patch', revision="5e5434dc43a8d1325aade8b0da65d96d7c4cf3d9", local_dir='./models/ID-Patch', local_dir_use_symlinks=False)
69
+ snapshot_download(repo_id='RunDiffusion/Juggernaut-X-v10', revision="main", local_dir='./models/Juggernaut-X-v10', local_dir_use_symlinks=False)
70
+
71
+
72
+ def init_pipeline():
73
+ pipeline = loaded_pipeline_config['pipeline']
74
+ gc.collect()
75
+
76
+ model_path = f'./models/ID-Patch'
77
+ print(f'loading model from {model_path}')
78
+
79
+ pipeline = IDPatchInferencer(base_model_path='./models/Juggernaut-X-v10', idp_model_path='./models/ID-Patch')
80
+
81
+ loaded_pipeline_config['pipeline'] = pipeline
82
+ return pipeline
83
+
84
+ # Future works: Add more model variants
85
+ def prepare_pipeline():
86
+ pipeline = loaded_pipeline_config['pipeline']
87
+ return pipeline
88
+
89
+
90
+ def add_safety_watermark(image, text='AI Generated: ID-Patch', font_path=None):
91
+ width, height = image.size
92
+ draw = ImageDraw.Draw(image)
93
+
94
+ font_size = int(height * 0.028)
95
+ if font_path:
96
+ font = ImageFont.truetype(font_path, font_size)
97
+ else:
98
+ font = ImageFont.load_default(size=font_size)
99
+
100
+ text_bbox = draw.textbbox((0, 0), text, font=font)
101
+ text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
102
+ x = width - text_width - 10
103
+ y = height - text_height - 20
104
+
105
+ shadow_offset = 2
106
+ shadow_color = "black"
107
+ draw.text((x + shadow_offset, y + shadow_offset), text, font=font, fill=shadow_color)
108
+
109
+ draw.text((x, y), text, font=font, fill="white")
110
+
111
+ return image
112
+
113
+
114
+ @spaces.GPU(duration=60)
115
+ def generate_image(
116
+ id_images,
117
+ id_order,
118
+ control_image,
119
+ prompt,
120
+ seed,
121
+ guidance_scale,
122
+ num_steps,
123
+ controlnet_conditioning_scale,
124
+ id_injection_ratio,
125
+ negative_prompt
126
+ ):
127
+ try:
128
+ print("======= Start Generating =======")
129
+ print(f"ID Images uploaded: {len(id_images)}")
130
+
131
+ id_images_pil = []
132
+ for idx, img in enumerate(id_images):
133
+ img = img[0]
134
+ print(f"ID Image {idx} size: {img.size}")
135
+ id_images_pil.append(img)
136
+ id_images = id_images_pil
137
+
138
+ if id_order is not None and id_order.strip() != "":
139
+ id_order = id_order.split(',')
140
+ sorted_id_images = [id_images[int(i)] for i in id_order]
141
+ id_images = sorted_id_images
142
+ else:
143
+ id_order = [i for i in range(len(id_images))]
144
+
145
+ print(f"Control Image size: {control_image.size}")
146
+
147
+ pipeline = prepare_pipeline()
148
+ device = "cuda" if torch.cuda.is_available() else "cpu"
149
+ arcface_encoder = facexlib.recognition.init_recognition_model('arcface', device=device)
150
+ tf.config.set_visible_devices([], 'GPU')
151
+ mtcnn_inferencer = MTCNN() # MTCNN might be slow, could be replaced by other face detectors, as long as it provides 5 keypoints
152
+
153
+ if seed == 0:
154
+ seed = torch.seed() & 0xFFFFFFFF
155
+
156
+ face_embs = []
157
+ for subject in id_images:
158
+ image_subject = pil_to_cv2(subject)
159
+
160
+ mtcnn_subject = mtcnn_inferencer.detect_faces(image_subject[:,:,::-1])
161
+ if not mtcnn_subject:
162
+ print("Warning: No face detected in uploaded identity image.")
163
+ continue # skip this image
164
+
165
+ try:
166
+ kps_subject = mtcnn_to_kps(mtcnn_subject)
167
+ cropped_face_subject = face_align.norm_crop(image_subject, landmark=kps_subject, image_size=112)
168
+ emb = extract_face_emb(arcface_encoder, cropped_face_subject)
169
+ face_embs.append(emb)
170
+ except Exception as e:
171
+ print(f"Error processing face: {e}")
172
+ continue
173
+
174
+ if len(face_embs) == 0:
175
+ raise ValueError("No valid face embeddings extracted. Please upload clear identity images.")
176
+
177
+ face_embs = torch.stack(face_embs)
178
+
179
+ # load pose
180
+ image_reference = pil_to_cv2(control_image)
181
+
182
+ # estimate pose
183
+ keypoints, scores = body_estimator(image_reference)
184
+
185
+ # Check
186
+ print(f"Keypoints raw output: {keypoints}")
187
+ if keypoints is None:
188
+ raise ValueError("Keypoints is None.")
189
+ if not isinstance(keypoints, (list, np.ndarray)):
190
+ raise ValueError(f"Keypoints type wrong: {type(keypoints)}")
191
+ if len(keypoints) == 0:
192
+ raise ValueError("Keypoints length == 0.")
193
+
194
+ keypoints = np.array(keypoints)
195
+ print(f"Keypoints converted to np.array, shape = {keypoints.shape}")
196
+
197
+ if len(keypoints.shape) != 3:
198
+ raise ValueError(f"Keypoints wrong shape: {keypoints.shape}")
199
+ if keypoints.shape[0] == 0:
200
+ raise ValueError("No people detected in the pose control image.")
201
+
202
+ face_locations = keypoints[:, 0]
203
+ face_locations = sorted(face_locations, key=lambda x: x[0] if isinstance(x, (list, tuple, np.ndarray)) and len(x) > 0 else 0)
204
+ face_locations = torch.from_numpy(np.stack(face_locations))
205
+
206
+ # Draw OpenPose image
207
+ control_image = Image.fromarray(draw_openpose_from_mmpose(image_reference * 0, keypoints, scores))
208
+
209
+ image = pipeline.generate(
210
+ face_embs,
211
+ face_locations,
212
+ control_image,
213
+ prompt=prompt,
214
+ negative_prompt=negative_prompt,
215
+ guidance_scale=guidance_scale,
216
+ num_inference_steps=num_steps,
217
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
218
+ id_injection_ratio=id_injection_ratio,
219
+ seed=seed
220
+ )
221
+ image = add_safety_watermark(image)
222
+
223
+ except Exception as e:
224
+ print(e)
225
+ gr.Error(f"An error occurred: {e}")
226
+ return gr.update()
227
+
228
+ return gr.update(value=image, label=f"Generated Image, seed = {seed}"), gr.update(value=control_image, label=f"OpenPose")
229
+
230
+
231
+ def generate_examples(id_image_paths, ui_id_order, control_image_path, prompt_text, seed):
232
+ id_images = [Image.open(p).convert('RGB') for p in id_image_paths]
233
+ control_image = Image.open(control_image_path).convert('RGB')
234
+ return generate_image(id_images, ui_id_order, control_image, prompt_text, seed, 5.5, 50, 0.8, 0.8, "nude, worst quality, low quality, normal quality, nsfw, abstract, glitch, deformed, mutated, ugly, disfigured, text, watermark, bad hands, error, jpeg artifacts, blurry, missing fingers")
235
+
236
+
237
+ def load_example(selected_key):
238
+ if selected_key is None:
239
+ return None, None, None, None, None
240
+
241
+ example = example_choices[selected_key]
242
+ id_images = [Image.open(p).convert('RGB') for p in example['id_images']]
243
+ control_image = Image.open(example['pose_image']).convert('RGB')
244
+ return (
245
+ id_images, # For ui_id_image (Gallery)
246
+ example['id_order'], # For ui_id_order (Textbox)
247
+ control_image, # For ui_control_image (Image)
248
+ example['prompt'], # For ui_prompt_text (Textbox)
249
+ example['seed'] # For ui_seed (Number)
250
+ )
251
+
252
+ # Get all available ID and pose images
253
+ man_images = sorted(list(Path('./assets/subjects/man').glob('*.jpg')))
254
+ woman_images = sorted(list(Path('./assets/subjects/woman').glob('*.jpg')))
255
+ pose_images = sorted(list(Path('./assets/poses').glob('*.png')) + list(Path('./assets/poses').glob('*.jpeg')) + list(Path('./assets/poses').glob('*.jpg')))
256
+
257
+ def random_select_id_images(num_men, num_women):
258
+ if int(num_men) > len(man_images) or int(num_women) > len(woman_images):
259
+ raise ValueError("Requested more images than available.")
260
+ selected_men = np.random.choice(man_images, size=int(num_men), replace=False)
261
+ selected_women = np.random.choice(woman_images, size=int(num_women), replace=False)
262
+ selected = list(selected_men) + list(selected_women)
263
+ images = [Image.open(p).convert('RGB') for p in selected]
264
+ id_order = ",".join(str(i) for i in range(len(images)))
265
+ return images, id_order
266
+
267
+
268
+
269
+
270
+ with gr.Blocks() as demo:
271
+ session_state = gr.State({})
272
+ default_model_version = "v1.0"
273
+
274
+ gr.HTML("""
275
+ <div style="text-align: center; max-width: 900px; margin: 0 auto;">
276
+ <h1 style="font-size: 1.5rem; font-weight: 700; display: block;">ID-Patch-SDXL</h1>
277
+ <h2 style="font-size: 1.2rem; font-weight: 300; margin-bottom: 1rem; display: block;">Official Gradio Demo for Our CVPR 2025 Paper <br><br>
278
+ <b>"ID-Patch: Robust ID Association for Group Photo Personalization" </b>
279
+ </h2>
280
+ <a href="https://byteaigc.github.io/ID-Patch/">[Project Page]</a>&ensp;
281
+ <a href="https://arxiv.org/abs/2411.13632">[Paper]</a>&ensp;
282
+ <a href="https://damon-demon.github.io/links/ID_Patch_CVPR25_poster.pdf">[Poster]</a>&ensp;
283
+ <a href="https://github.com/bytedance/ID-Patch">[Code]</a>&ensp;
284
+ <a href="https://huggingface.co/ByteDance/ID-Patch">[Model]</a>
285
+ </div>
286
+ """)
287
+
288
+ # Add the pipeline image of ID-Patch: assets/pipeline.png and short description
289
+ # with gr.Column(elem_id="pipeline_block"):
290
+ # gr.Image(
291
+ # value="./assets/pipeline.png",
292
+ # interactive=False,
293
+ # show_label=False,
294
+ # height=300,
295
+ # container=False
296
+ # )
297
+ # gr.HTML(
298
+ # """
299
+ # <div style="text-align:center; font-size:1.2rem; font-weight:300;">
300
+ # Pipeline of ID-Patch: Build Identity-to-Position Association
301
+ # </div>
302
+ # """
303
+ # )
304
+
305
+
306
+ gr.Markdown("""
307
+ ### 💡 How to Use This Demo?
308
+ 1. **Upload ID images**:
309
+ - Upload one or more ID images for each person you want to generate.
310
+ *(The number of uploaded ID images should match the number of people in your pose reference image.)*
311
+
312
+ 2. **ID Order**:
313
+ - List the ID images separated by commas, following the **left-to-right order** of detected faces in the pose reference image.
314
+ *(ID index starts from 0!)*
315
+
316
+
317
+ 3. **Upload a pose reference image**:
318
+ - Choose an image that shows the desired pose(s) for the people you want to generate.
319
+ *(Tip: If the pose is too complicated, then the face detection and pose detection might fail.)*
320
+
321
+ 4. **Enter a text prompt**:
322
+ - Describe the scene you want to create.
323
+ *(Tip: Try to match the interactions described in your text with the uploaded pose reference.)*
324
+
325
+ 5. **[Optional] Adjust advanced settings**:
326
+ Fine-tune generation details if needed.
327
+
328
+ 6. **Click "Generate"**:
329
+ Your personalized image will be created. Enjoy!
330
+
331
+ We also offer example data that users can easily select and load by clicking the **“Load Example”** button for testing.
332
+
333
+ Alternatively, you can randomly sample a specific number of male and female face images from our provided identity image dataset and choose a pose from the available options.
334
+ """)
335
+
336
+ with gr.Row():
337
+ with gr.Column(scale=3):
338
+
339
+ example_choices = {
340
+ "Woman Playing Piano (1 People)": {
341
+ "id_images": ['./assets/subjects/woman/66.jpg'],
342
+ "id_order": "0",
343
+ "pose_image": './assets/poses/p1_1.jpeg',
344
+ "prompt": 'a woman is playing piano, (pianist:1.1), wearing an elegant metallic gold backless gown dress, silver earrings, on the stage, in the spotlight, bright and colorful lighting, LED screen background, vibrant fill light',
345
+ "seed": 1111
346
+ },
347
+ "Man Playing Piano (1 People)": {
348
+ "id_images": ['./assets/subjects/man/21.jpg'],
349
+ "id_order": "0",
350
+ "pose_image": './assets/poses/p1_2.jpeg',
351
+ "prompt": 'a man is playing piano, (pianist:1.1), wearing an elegant black havana tuxedo, on the stage, in the spotlight, bright and colorful lighting, LED screen background',
352
+ "seed": 1111
353
+ },
354
+ "Couple Cheers (2 People)": {
355
+ "id_images": ['./assets/subjects/man/0.jpg', './assets/subjects/woman/0.jpg'],
356
+ "id_order": "0,1",
357
+ "pose_image": './assets/poses/p2.png',
358
+ "prompt": 'a young couple in front of their burning home still managing to find a moment of joy amidst disaster. cheerfully raise glasses filled with a bright blue drink',
359
+ "seed": 2222
360
+ },
361
+ "Friend Selfie (3 People)": {
362
+ "id_images": ['./assets/subjects/woman/26.jpg', './assets/subjects/woman/53.jpg','./assets/subjects/man/52.jpg'],
363
+ "id_order": "0,1,2",
364
+ "pose_image": './assets/poses/p3_2.jpeg',
365
+ "prompt": 'a joyful selfie of three friends, background of television studio setting.',
366
+ "seed": 3333
367
+ },
368
+ "Happy Piano Moment (4 People)": {
369
+ "id_images": ['./assets/subjects/man/40.jpg', './assets/subjects/woman/59.jpg','./assets/subjects/woman/79.jpg', './assets/subjects/man/43.jpg'],
370
+ "id_order": "0,1,2,3",
371
+ "pose_image": './assets/poses/p4.jpeg',
372
+ "prompt": 'three adults watch one man playing the piano in a brightly lit, elegant room with vintage decor',
373
+ "seed": 4444
374
+ },
375
+ "Outdoor Selfie (6 People)": {
376
+ "id_images": ['./assets/subjects/man/51.jpg', './assets/subjects/man/52.jpg','./assets/subjects/woman/79.jpg', './assets/subjects/woman/66.jpg', './assets/subjects/woman/39.jpg', './assets/subjects/man/49.jpg'],
377
+ "id_order": "0,1,2,3,4,5",
378
+ "pose_image": './assets/poses/p6.jpeg',
379
+ "prompt": 'A joyful group selfie of six adventurous people on a mountain at sunrise. Each person is dressed in outdoor apparel suitable for chilly weather',
380
+ "seed": 6666
381
+ },
382
+ }
383
+
384
+ # Build pose_name_to_path mapping
385
+ pose_name_to_path = {
386
+ example_name: example_data["pose_image"]
387
+ for example_name, example_data in example_choices.items()
388
+ }
389
+
390
+
391
+ with gr.Column(scale=2):
392
+ selected_example = gr.Dropdown(
393
+ choices=list(example_choices.keys()),
394
+ label="Example Selection",
395
+ interactive=True
396
+ )
397
+ load_example_btn = gr.Button("Load Example")
398
+
399
+ with gr.Row():
400
+ with gr.Column(scale=3):
401
+ ui_id_image = gr.Gallery(
402
+ label="Identity Images",
403
+ type="pil",
404
+ scale=3,
405
+ height=370,
406
+ min_width=100,
407
+ columns=4,
408
+ rows=1,
409
+ allow_preview=True,
410
+ show_label=True,
411
+ interactive=True
412
+ )
413
+
414
+ # Random Identity Selection
415
+ with gr.Row():
416
+ num_men_dropdown = gr.Dropdown(
417
+ choices=[str(i) for i in range(11)],
418
+ value="0",
419
+ label="Number of Men"
420
+ )
421
+ num_women_dropdown = gr.Dropdown(
422
+ choices=[str(i) for i in range(11)],
423
+ value="0",
424
+ label="Number of Women"
425
+ )
426
+ random_select_button = gr.Button("Random Select IDs")
427
+
428
+
429
+ with gr.Column(scale=2, min_width=100):
430
+ ui_control_image = gr.Image(label="Pose Reference Image", type="pil", height=370, min_width=100)
431
+
432
+ # Pose Selection based on Example Choices
433
+ pose_dropdown = gr.Dropdown(
434
+ choices=list(pose_name_to_path.keys()),
435
+ label="Select Pose Example",
436
+ interactive=True
437
+ )
438
+ pose_select_button = gr.Button("Load Pose")
439
+
440
+
441
+ ui_prompt_text = gr.Textbox(label="Text Prompt (Describe the image you would like to generate)", value="Portrait, 4K, high quality, cinematic")
442
+ ui_id_order = gr.Textbox(label="ID Order (If not specified, the images will follow the original upload order)", value = None)
443
+
444
+
445
+ ui_btn_generate = gr.Button("Generate")
446
+
447
+ with gr.Accordion("Advanced Settings", open=True):
448
+ with gr.Row():
449
+ ui_num_steps = gr.Number(label="Steps", value=50)
450
+ ui_seed = gr.Number(label="Seed (0 for random seed)", value=0)
451
+ ui_guidance_scale = gr.Number(label="Guidance Scale", value=5.5, step=0.1)
452
+ ui_controlnet_conditioning_scale = gr.Slider(minimum=0.0, maximum=1.0, value=0.8, step=0.05, label="ControlNet Conditioning Scale")
453
+ ui_id_injection_ratio = gr.Slider(minimum=0.0, maximum=1.0, value=0.8, step=0.05, label="ID Injection Ratio")
454
+ ui_negative_prompt = gr.Textbox(label="Negative Prompt", value="nude, worst quality, low quality, normal quality, nsfw, abstract, glitch, deformed, mutated, ugly, disfigured, text, watermark, bad hands, error, jpeg artifacts, blurry, missing fingers")
455
+
456
+
457
+
458
+ with gr.Column(scale=2):
459
+ image_output = gr.Image(label="Generated Image", interactive=False, height=880, format='png')
460
+ openpose_control_image = gr.Image(label="OpenPose Image", interactive=False, height=549, format='png')
461
+
462
+
463
+
464
+ ui_btn_generate.click(
465
+ generate_image,
466
+ inputs=[
467
+ ui_id_image,
468
+ ui_id_order,
469
+ ui_control_image,
470
+ ui_prompt_text,
471
+ ui_seed,
472
+ ui_guidance_scale,
473
+ ui_num_steps,
474
+ ui_controlnet_conditioning_scale,
475
+ ui_id_injection_ratio,
476
+ ui_negative_prompt
477
+
478
+ ],
479
+ outputs=[image_output, openpose_control_image],
480
+ concurrency_id="gpu"
481
+ )
482
+
483
+ load_example_btn.click(
484
+ load_example,
485
+ inputs=[selected_example],
486
+ outputs=[ui_id_image, ui_id_order, ui_control_image, ui_prompt_text, ui_seed]
487
+ )
488
+
489
+ random_select_button.click(
490
+ random_select_id_images,
491
+ inputs=[num_men_dropdown, num_women_dropdown],
492
+ outputs=[ui_id_image, ui_id_order]
493
+ )
494
+
495
+ def select_pose_image(pose_name):
496
+ if pose_name not in pose_name_to_path:
497
+ raise ValueError(f"Pose name {pose_name} not found.")
498
+
499
+ pose_path = pose_name_to_path[pose_name]
500
+ pose_image = Image.open(pose_path).convert('RGB')
501
+
502
+ for example_name, example_data in example_choices.items():
503
+ if example_name == pose_name:
504
+ prompt = example_data['prompt']
505
+ break
506
+ else:
507
+ prompt = ""
508
+
509
+ return pose_image, prompt
510
+
511
+ pose_select_button.click(
512
+ select_pose_image,
513
+ inputs=[pose_dropdown],
514
+ outputs=[ui_control_image, ui_prompt_text]
515
+ )
516
+
517
+
518
+ gr.Markdown(
519
+ """
520
+ ---
521
+ ### 📜 Disclaimer and Licenses
522
+ The images used in this demo are sourced from consented subjects or generated by the models. These pictures are intended solely to show the capabilities of our research. If you have any concerns, please contact us, and we will promptly remove any inappropriate content.
523
+
524
+ The use of the released code, model, and demo must strictly adhere to the respective licenses.
525
+ Our code is released under the [Apache License 2.0](https://github.com/bytedance/ID-Patch/blob/main/LICENSE),
526
+ and our model is released under the [CreativeML Open RAIL++-M License](https://huggingface.co/ByteDance/ID-Patch/blob/main/LICENSE.md)
527
+ for academic research purposes only. Any manual or automatic downloading of the face models from [InsightFace](https://github.com/deepinsight/insightface),
528
+ the [Juggernaut-X-v10](https://huggingface.co/RunDiffusion/Juggernaut-X-v10) base model, *etc.*, must follow their original licenses and be used only for academic research purposes.
529
+
530
+ This research aims to positively impact the field of Generative AI. Any usage of this method must be responsible and comply with local laws. The developers do not assume any responsibility for any potential misuse. We added the "AI Generated: ID-Patch" watermark for enhanced safety.
531
+ """
532
+ )
533
+
534
+ gr.Markdown(
535
+ """
536
+ ### 📖 Citation
537
+
538
+ If you find ID-Patch useful for your research or applications, please cite our paper:
539
+
540
+ ```bibtex
541
+ @InProceedings{zhang2025idpatch,
542
+ author = {Zhang, Yimeng and Zhi, Tiancheng and Liu, Jing and Sang, Shen and Jiang, Liming and Yan, Qing and Liu, Sijia and Luo, Linjie},
543
+ title = {ID-Patch: Robust ID Association for Group Photo Personalization},
544
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
545
+ month = {June},
546
+ year = {2025}
547
+ }
548
+ ```
549
+
550
+ We also appreciate it if you could give a star ⭐ to our [Github repository](https://github.com/bytedance/ID-Patch). Thanks a lot!
551
+ """
552
+ )
553
+
554
+
555
+ download_models()
556
+ init_pipeline()
557
+ demo.launch()
assets/pipeline.png ADDED

Git LFS Details

  • SHA256: 0c610f734425b539f56c3f412eedd91ec1410603e08102f8f763cf76bf3ed25b
  • Pointer size: 131 Bytes
  • Size of remote file: 372 kB
assets/poses/p1_1.jpeg ADDED

Git LFS Details

  • SHA256: 52ffde7b8ad6aaa5520bd591def3dd3c1b523d0825770df484de0fee0f092464
  • Pointer size: 131 Bytes
  • Size of remote file: 893 kB
assets/poses/p1_2.jpeg ADDED

Git LFS Details

  • SHA256: 72d361c5f42f88a6c49dcdbd61b1cf49b15c2cd2ed660cb0207c2542f2cc7592
  • Pointer size: 131 Bytes
  • Size of remote file: 599 kB
assets/poses/p2.png ADDED

Git LFS Details

  • SHA256: 3c44a913b9fda847e049928e46f4bed4b406e3cb7d949ababf404cd072855686
  • Pointer size: 132 Bytes
  • Size of remote file: 1.56 MB
assets/poses/p3_1.jpeg ADDED

Git LFS Details

  • SHA256: 88b6a2553a2f5b6f77c974c22654059f5ec5f73487cb0a1c5b5dfd8284e561e5
  • Pointer size: 131 Bytes
  • Size of remote file: 706 kB
assets/poses/p3_2.jpeg ADDED

Git LFS Details

  • SHA256: e7fb92ae07731c163d976029c9815bb7b32dae325c21ee6f310022ac9ef63b95
  • Pointer size: 131 Bytes
  • Size of remote file: 793 kB
assets/poses/p4.jpeg ADDED

Git LFS Details

  • SHA256: dffe9d97d9e4bc70fad451d553ce053f6cc48728b0846da3e81c21aebaeb93cf
  • Pointer size: 131 Bytes
  • Size of remote file: 676 kB
assets/poses/p5.jpeg ADDED

Git LFS Details

  • SHA256: e2e4f6d60206695fc0d79115a6d5fcfcbf8ae9c7f2963c417570a4defc482b64
  • Pointer size: 131 Bytes
  • Size of remote file: 759 kB
assets/poses/p6.jpeg ADDED

Git LFS Details

  • SHA256: 806da59e4679c7e48234b2818a2afcae83a51c63fe8148944e9faf6bd47085de
  • Pointer size: 131 Bytes
  • Size of remote file: 665 kB
assets/subjects/man/0.jpg ADDED

Git LFS Details

  • SHA256: af33286230ab1ecf6844240301b6b871591944118bfa1764fcd2fa0e1f6d4c24
  • Pointer size: 131 Bytes
  • Size of remote file: 210 kB
assets/subjects/man/12.jpg ADDED

Git LFS Details

  • SHA256: cf775af184dd138aad68f8820bc42c5b81d3f3c9c6bbcc3e91fdfe5c4c3f0afa
  • Pointer size: 131 Bytes
  • Size of remote file: 518 kB
assets/subjects/man/13.jpg ADDED

Git LFS Details

  • SHA256: 570dbb6e3a971ca11274de189c8ff39d08d7939d7a7e6990a4438b2760d72359
  • Pointer size: 131 Bytes
  • Size of remote file: 171 kB
assets/subjects/man/21.jpg ADDED

Git LFS Details

  • SHA256: 0a5e0ee64da14245662d25adb49d8a70a0f994fdf38d32bd9ad7c9de9480dd5a
  • Pointer size: 131 Bytes
  • Size of remote file: 101 kB
assets/subjects/man/27.jpg ADDED

Git LFS Details

  • SHA256: 3e01eb6708676208059757336ccbd8ff60a578c8a6053126acc89a94af503a84
  • Pointer size: 131 Bytes
  • Size of remote file: 249 kB
assets/subjects/man/40.jpg ADDED

Git LFS Details

  • SHA256: a98a4ea6d58fe181fbd3b6555816814cb0c204e4c7782fd25882058e27129856
  • Pointer size: 132 Bytes
  • Size of remote file: 1.48 MB
assets/subjects/man/43.jpg ADDED

Git LFS Details

  • SHA256: d91f0e31bf85d86fb368cb996e960ebcfe91c8173b96a7863b27f9b526f02f67
  • Pointer size: 131 Bytes
  • Size of remote file: 283 kB
assets/subjects/man/44.jpg ADDED

Git LFS Details

  • SHA256: d35b21193154ea4738c05f9b556f0267a2514c87147f57c714f75b63f86772b5
  • Pointer size: 132 Bytes
  • Size of remote file: 1.46 MB
assets/subjects/man/49.jpg ADDED

Git LFS Details

  • SHA256: 758b6adfe7172dc720dcc1c3006d1f9366007645a781c30f2f13705738879f02
  • Pointer size: 131 Bytes
  • Size of remote file: 369 kB
assets/subjects/man/51.jpg ADDED

Git LFS Details

  • SHA256: 97a90405e2a17ab5f716f129745a8490c1c3282229b7985339811e939fed24a8
  • Pointer size: 131 Bytes
  • Size of remote file: 359 kB
assets/subjects/man/52.jpg ADDED

Git LFS Details

  • SHA256: 00b5866616180af92052d276eae5c1ddaf65cc8d89ddc45596c0d4d47cbc7670
  • Pointer size: 131 Bytes
  • Size of remote file: 810 kB
assets/subjects/woman/0.jpg ADDED

Git LFS Details

  • SHA256: e4d717ccff241da65ef3bec67d4eb0079cb4f2a2bc9a0e7d135452d988d8cd9c
  • Pointer size: 131 Bytes
  • Size of remote file: 149 kB
assets/subjects/woman/16.jpg ADDED

Git LFS Details

  • SHA256: 3e538d90efeff0d79873aa0b4470fd08d30574c563621abab5e2404884f56c7c
  • Pointer size: 131 Bytes
  • Size of remote file: 113 kB
assets/subjects/woman/26.jpg ADDED

Git LFS Details

  • SHA256: bb53f04e5c7b28544c15571f3684a057e05c7f0189bcbb9cf7a706ba924fb17b
  • Pointer size: 131 Bytes
  • Size of remote file: 129 kB
assets/subjects/woman/35.jpg ADDED

Git LFS Details

  • SHA256: ee91760ae67100da70c4dae13b1abb9ccb70ea41dc6ddfb2078728f65d9d6b27
  • Pointer size: 131 Bytes
  • Size of remote file: 161 kB
assets/subjects/woman/38.jpg ADDED

Git LFS Details

  • SHA256: 97e273392fdb295789eefc6bb85619d7a0ee2388ea516359e509e4d52da14aae
  • Pointer size: 131 Bytes
  • Size of remote file: 252 kB
assets/subjects/woman/39.jpg ADDED
assets/subjects/woman/53.jpg ADDED

Git LFS Details

  • SHA256: 09bdfc12e3c6d715b406152599aabc41b3eb7ccb051153fef518005b2ef59a43
  • Pointer size: 131 Bytes
  • Size of remote file: 890 kB
assets/subjects/woman/59.jpg ADDED

Git LFS Details

  • SHA256: 337007c0ac48f873bac9d7cbefffa16930c928f024dc8071e846493fa732f58e
  • Pointer size: 131 Bytes
  • Size of remote file: 215 kB
assets/subjects/woman/66.jpg ADDED

Git LFS Details

  • SHA256: d1072f5beb4ed7f4ed835d43d5d821ca7617d681e36bb1a23a1784a5a4454bfe
  • Pointer size: 132 Bytes
  • Size of remote file: 1.59 MB
assets/subjects/woman/79.jpg ADDED
assets/subjects/woman/99.jpg ADDED

Git LFS Details

  • SHA256: f1b5bb5670572d7f1a6cd72524088db5af4592db7bdc36dbb3a526a39bee3531
  • Pointer size: 131 Bytes
  • Size of remote file: 147 kB
assets/teaser.png ADDED

Git LFS Details

  • SHA256: 6374b6d50508f597dbf3aca0b7e6e2f8ee825a7235695824805cd0e89b77a041
  • Pointer size: 132 Bytes
  • Size of remote file: 4.16 MB
modules/__init__.py ADDED
File without changes
modules/inferencer.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ import torch
5
+ from pathlib import Path
6
+ import numpy as np
7
+ from diffusers import ControlNetModel, EulerDiscreteScheduler
8
+ from diffusers.loaders.unet import UNet2DConditionLoadersMixin
9
+
10
+ from .pipeline_idpatch_sd_xl import StableDiffusionXLIDPatchPipeline
11
+
12
+ class IDPatchInferencer:
13
+ def __init__(self, base_model_path, idp_model_path, patch_size=64, torch_device='cuda:0', torch_dtype=torch.bfloat16):
14
+ super().__init__()
15
+ self.patch_size = patch_size
16
+ self.torch_device = torch_device
17
+ self.torch_dtype = torch_dtype
18
+ idp_state_dict = torch.load(Path(idp_model_path) / 'id-patch.bin', map_location="cpu")
19
+ loader = UNet2DConditionLoadersMixin()
20
+ self.id_patch_projection = loader._convert_ip_adapter_image_proj_to_diffusers(idp_state_dict['patch_proj']).to(self.torch_device, dtype=self.torch_dtype).eval()
21
+ self.id_prompt_projection = loader._convert_ip_adapter_image_proj_to_diffusers(idp_state_dict['prompt_proj']).to(self.torch_device, dtype=self.torch_dtype).eval()
22
+ controlnet = ControlNetModel.from_pretrained(Path(idp_model_path) / 'ControlNetModel').to(self.torch_device, dtype=self.torch_dtype).eval()
23
+ scheduler = EulerDiscreteScheduler.from_pretrained(base_model_path, subfolder="scheduler")
24
+ self.pipe = StableDiffusionXLIDPatchPipeline.from_pretrained(
25
+ base_model_path,
26
+ controlnet=controlnet,
27
+ scheduler=scheduler,
28
+ torch_dtype=self.torch_dtype,
29
+ ).to(self.torch_device)
30
+
31
+ def get_text_embeds_from_strings(self, text_strings):
32
+ pipe = self.pipe
33
+ device = pipe.device
34
+ tokenizer_1 = pipe.tokenizer
35
+ tokenizer_2 = pipe.tokenizer_2
36
+ text_encoder_1 = pipe.text_encoder
37
+ text_encoder_2 = pipe.text_encoder_2
38
+
39
+ text_embeds = []
40
+ for tokenizer, text_encoder in [(tokenizer_1, text_encoder_1), (tokenizer_2, text_encoder_2)]:
41
+ input_ids = tokenizer(
42
+ text_strings,
43
+ max_length=tokenizer.model_max_length,
44
+ padding="max_length",
45
+ truncation=True,
46
+ return_tensors="pt"
47
+ ).input_ids.to(device)
48
+ text_embeds.append(text_encoder(input_ids, output_hidden_states=True))
49
+ pooled_embeds = text_embeds[1]['text_embeds']
50
+ text_embeds = torch.concat([text_embeds[0]['hidden_states'][-2], text_embeds[1]['hidden_states'][-2]], dim=2)
51
+ return text_embeds, pooled_embeds
52
+
53
+ def generate(self, face_embeds, face_locations, control_image, prompt, negative_prompt="", guidance_scale=5.0, num_inference_steps=50, controlnet_conditioning_scale=0.8, id_injection_ratio=0.8, seed=-1):
54
+ """
55
+ face_embeds: n_faces x 512
56
+ face_locations: n_faces x 2[xy]
57
+ control_image: PIL image
58
+ """
59
+
60
+ face_locations = face_locations.to(self.torch_device, self.torch_dtype)
61
+ control_image = torch.from_numpy(np.array(control_image)).to(self.torch_device, dtype=self.torch_dtype).permute(2,0,1)[None] / 255.0
62
+ height, width = control_image.shape[2:4]
63
+
64
+ text_embeds, pooled_embeds = self.get_text_embeds_from_strings([negative_prompt, prompt]) # text_embeds: 2 x 77 x 2048, pooled_embeds: 2 x 1280
65
+ negative_pooled_embeds, pooled_embeds = pooled_embeds[:1], pooled_embeds[1:]
66
+ negative_text_embeds, text_embeds = text_embeds[:1], text_embeds[1:]
67
+
68
+ n_faces = len(face_embeds)
69
+ negative_id_embeds = self.id_prompt_projection(torch.zeros(n_faces, 1, 512, device=self.torch_device, dtype=self.torch_dtype)) # (BxF) x 16 x 2048
70
+ negative_id_embeds = negative_id_embeds.reshape(1, -1, negative_id_embeds.shape[2]) # B x (Fx16) x 2048
71
+ negative_text_id_embeds = torch.concat([negative_text_embeds, negative_id_embeds], dim=1)
72
+
73
+ face_embeds = face_embeds[None].to(self.torch_device, self.torch_dtype) # 1 x faces x 512
74
+ id_embeds = self.id_prompt_projection(face_embeds.reshape(-1, 1, 512)) # (BxF) x 16 x 2048
75
+ id_embeds = id_embeds.reshape(face_embeds.shape[0], -1, id_embeds.shape[2]) # B x (Fx16) x 2048
76
+ text_id_embeds = torch.concat([text_embeds, id_embeds], dim=1) # B x (77+Fx16) x 2048
77
+
78
+ patch_prompt_embeds = self.id_patch_projection(face_embeds.reshape(-1, 1, 512)) # (Bxn_faces) x 3 x (64*64)
79
+ patch_prompt_embeds = patch_prompt_embeds.reshape(1, n_faces, 3, self.patch_size, self.patch_size)
80
+ pad = self.patch_size // 2
81
+ canvas = torch.zeros((1, 3, height + pad * 2, width + pad * 2), device=self.torch_device)
82
+
83
+ xymin = torch.round(face_locations - self.patch_size // 2).int()
84
+ xymax =torch.round(face_locations + self.patch_size // 2).int()
85
+ for f in range(n_faces):
86
+ xmin, ymin = xymin[f,0], xymin[f,1]
87
+ xmax, ymax = xymax[f,0], xymax[f,1]
88
+ if xmin+pad < 0 or xmax-pad >= width or ymin+pad < 0 or ymax-pad >= height:
89
+ continue
90
+ canvas[0,:,ymin+pad:ymax+pad,xmin+pad:xmax+pad] += patch_prompt_embeds[0,f]
91
+ condition_image = control_image + canvas[:,:,pad:-pad,pad:-pad]
92
+
93
+ if seed >= 0:
94
+ generator = torch.Generator(self.torch_device).manual_seed(seed)
95
+ else:
96
+ generator = None
97
+ output_image = self.pipe(
98
+ prompt_embeds=text_id_embeds,
99
+ pooled_prompt_embeds=pooled_embeds,
100
+ negative_prompt_embeds=negative_text_id_embeds,
101
+ negative_pooled_prompt_embeds=negative_pooled_embeds,
102
+ image=condition_image,
103
+ guidance_scale=guidance_scale,
104
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
105
+ num_inference_steps=num_inference_steps,
106
+ id_injection_ratio=id_injection_ratio,
107
+ output_type='pil',
108
+ generator=generator,
109
+ ).images[0]
110
+ return output_image
modules/pipeline_idpatch_sd_xl.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 The HuggingFace Team
2
+ # Copyright (c) 2024 Bytedance Ltd. and/or its affiliates
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # This file has been modified by Bytedance Ltd. and/or its affiliates on October 10, 2024.
6
+ #
7
+ # Original file was released under Apache License 2.0, with the full license text
8
+ # available at https://github.com/huggingface/diffusers/blob/v0.30.3/LICENSE.
9
+ #
10
+ # This modified file is released under the same license.
11
+
12
+
13
+ from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl import *
14
+
15
+ class StableDiffusionXLIDPatchPipeline(StableDiffusionXLControlNetPipeline):
16
+
17
+ @torch.no_grad()
18
+ def __call__(
19
+ self,
20
+ prompt: Union[str, List[str]] = None,
21
+ prompt_2: Optional[Union[str, List[str]]] = None,
22
+ image: PipelineImageInput = None,
23
+ height: Optional[int] = None,
24
+ width: Optional[int] = None,
25
+ num_inference_steps: int = 50,
26
+ timesteps: List[int] = None,
27
+ sigmas: List[float] = None,
28
+ denoising_end: Optional[float] = None,
29
+ guidance_scale: float = 5.0,
30
+ negative_prompt: Optional[Union[str, List[str]]] = None,
31
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
32
+ num_images_per_prompt: Optional[int] = 1,
33
+ eta: float = 0.0,
34
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
35
+ latents: Optional[torch.Tensor] = None,
36
+ prompt_embeds: Optional[torch.Tensor] = None,
37
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
38
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
39
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
40
+ ip_adapter_image: Optional[PipelineImageInput] = None,
41
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
42
+ output_type: Optional[str] = "pil",
43
+ return_dict: bool = True,
44
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
45
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
46
+ guess_mode: bool = False,
47
+ control_guidance_start: Union[float, List[float]] = 0.0,
48
+ control_guidance_end: Union[float, List[float]] = 1.0,
49
+ original_size: Tuple[int, int] = None,
50
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
51
+ target_size: Tuple[int, int] = None,
52
+ negative_original_size: Optional[Tuple[int, int]] = None,
53
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
54
+ negative_target_size: Optional[Tuple[int, int]] = None,
55
+ clip_skip: Optional[int] = None,
56
+ callback_on_step_end: Optional[
57
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
58
+ ] = None,
59
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
60
+ id_injection_ratio: float = 1.0,
61
+ **kwargs,
62
+ ):
63
+
64
+ callback = kwargs.pop("callback", None)
65
+ callback_steps = kwargs.pop("callback_steps", None)
66
+
67
+ if callback is not None:
68
+ deprecate(
69
+ "callback",
70
+ "1.0.0",
71
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
72
+ )
73
+ if callback_steps is not None:
74
+ deprecate(
75
+ "callback_steps",
76
+ "1.0.0",
77
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
78
+ )
79
+
80
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
81
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
82
+
83
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
84
+
85
+ # align format for control guidance
86
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
87
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
88
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
89
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
90
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
91
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
92
+ control_guidance_start, control_guidance_end = (
93
+ mult * [control_guidance_start],
94
+ mult * [control_guidance_end],
95
+ )
96
+
97
+ # 1. Check inputs. Raise error if not correct
98
+ self.check_inputs(
99
+ prompt,
100
+ prompt_2,
101
+ image,
102
+ callback_steps,
103
+ negative_prompt,
104
+ negative_prompt_2,
105
+ prompt_embeds,
106
+ negative_prompt_embeds,
107
+ pooled_prompt_embeds,
108
+ ip_adapter_image,
109
+ ip_adapter_image_embeds,
110
+ negative_pooled_prompt_embeds,
111
+ controlnet_conditioning_scale,
112
+ control_guidance_start,
113
+ control_guidance_end,
114
+ callback_on_step_end_tensor_inputs,
115
+ )
116
+
117
+ self._guidance_scale = guidance_scale
118
+ self._clip_skip = clip_skip
119
+ self._cross_attention_kwargs = cross_attention_kwargs
120
+ self._denoising_end = denoising_end
121
+
122
+ # 2. Define call parameters
123
+ if prompt is not None and isinstance(prompt, str):
124
+ batch_size = 1
125
+ elif prompt is not None and isinstance(prompt, list):
126
+ batch_size = len(prompt)
127
+ else:
128
+ batch_size = prompt_embeds.shape[0]
129
+
130
+ device = self._execution_device
131
+
132
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
133
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
134
+
135
+ global_pool_conditions = (
136
+ controlnet.config.global_pool_conditions
137
+ if isinstance(controlnet, ControlNetModel)
138
+ else controlnet.nets[0].config.global_pool_conditions
139
+ )
140
+ guess_mode = guess_mode or global_pool_conditions
141
+
142
+ # 3.1 Encode input prompt
143
+ text_encoder_lora_scale = (
144
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
145
+ )
146
+ (
147
+ prompt_embeds,
148
+ negative_prompt_embeds,
149
+ pooled_prompt_embeds,
150
+ negative_pooled_prompt_embeds,
151
+ ) = self.encode_prompt(
152
+ prompt,
153
+ prompt_2,
154
+ device,
155
+ num_images_per_prompt,
156
+ self.do_classifier_free_guidance,
157
+ negative_prompt,
158
+ negative_prompt_2,
159
+ prompt_embeds=prompt_embeds,
160
+ negative_prompt_embeds=negative_prompt_embeds,
161
+ pooled_prompt_embeds=pooled_prompt_embeds,
162
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
163
+ lora_scale=text_encoder_lora_scale,
164
+ clip_skip=self.clip_skip,
165
+ )
166
+
167
+ # 3.2 Encode ip_adapter_image
168
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
169
+ image_embeds = self.prepare_ip_adapter_image_embeds(
170
+ ip_adapter_image,
171
+ ip_adapter_image_embeds,
172
+ device,
173
+ batch_size * num_images_per_prompt,
174
+ self.do_classifier_free_guidance,
175
+ )
176
+
177
+ # 4. Prepare image
178
+ if isinstance(controlnet, ControlNetModel):
179
+ image = self.prepare_image(
180
+ image=image,
181
+ width=width,
182
+ height=height,
183
+ batch_size=batch_size * num_images_per_prompt,
184
+ num_images_per_prompt=num_images_per_prompt,
185
+ device=device,
186
+ dtype=controlnet.dtype,
187
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
188
+ guess_mode=guess_mode,
189
+ )
190
+ height, width = image.shape[-2:]
191
+ elif isinstance(controlnet, MultiControlNetModel):
192
+ images = []
193
+
194
+ for image_ in image:
195
+ image_ = self.prepare_image(
196
+ image=image_,
197
+ width=width,
198
+ height=height,
199
+ batch_size=batch_size * num_images_per_prompt,
200
+ num_images_per_prompt=num_images_per_prompt,
201
+ device=device,
202
+ dtype=controlnet.dtype,
203
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
204
+ guess_mode=guess_mode,
205
+ )
206
+
207
+ images.append(image_)
208
+
209
+ image = images
210
+ height, width = image[0].shape[-2:]
211
+ else:
212
+ assert False
213
+
214
+ # 5. Prepare timesteps
215
+ timesteps, num_inference_steps = retrieve_timesteps(
216
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
217
+ )
218
+ self._num_timesteps = len(timesteps)
219
+
220
+ # 6. Prepare latent variables
221
+ num_channels_latents = self.unet.config.in_channels
222
+ latents = self.prepare_latents(
223
+ batch_size * num_images_per_prompt,
224
+ num_channels_latents,
225
+ height,
226
+ width,
227
+ prompt_embeds.dtype,
228
+ device,
229
+ generator,
230
+ latents,
231
+ )
232
+
233
+ # 6.5 Optionally get Guidance Scale Embedding
234
+ timestep_cond = None
235
+ if self.unet.config.time_cond_proj_dim is not None:
236
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
237
+ timestep_cond = self.get_guidance_scale_embedding(
238
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
239
+ ).to(device=device, dtype=latents.dtype)
240
+
241
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
242
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
243
+
244
+ # 7.1 Create tensor stating which controlnets to keep
245
+ controlnet_keep = []
246
+ for i in range(len(timesteps)):
247
+ keeps = [
248
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
249
+ for s, e in zip(control_guidance_start, control_guidance_end)
250
+ ]
251
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
252
+
253
+ # 7.2 Prepare added time ids & embeddings
254
+ if isinstance(image, list):
255
+ original_size = original_size or image[0].shape[-2:]
256
+ else:
257
+ original_size = original_size or image.shape[-2:]
258
+ target_size = target_size or (height, width)
259
+
260
+ add_text_embeds = pooled_prompt_embeds
261
+ if self.text_encoder_2 is None:
262
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
263
+ else:
264
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
265
+
266
+ add_time_ids = self._get_add_time_ids(
267
+ original_size,
268
+ crops_coords_top_left,
269
+ target_size,
270
+ dtype=prompt_embeds.dtype,
271
+ text_encoder_projection_dim=text_encoder_projection_dim,
272
+ )
273
+
274
+ if negative_original_size is not None and negative_target_size is not None:
275
+ negative_add_time_ids = self._get_add_time_ids(
276
+ negative_original_size,
277
+ negative_crops_coords_top_left,
278
+ negative_target_size,
279
+ dtype=prompt_embeds.dtype,
280
+ text_encoder_projection_dim=text_encoder_projection_dim,
281
+ )
282
+ else:
283
+ negative_add_time_ids = add_time_ids
284
+
285
+ if self.do_classifier_free_guidance:
286
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
287
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
288
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
289
+
290
+ prompt_embeds = prompt_embeds.to(device)
291
+ add_text_embeds = add_text_embeds.to(device)
292
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
293
+
294
+ # 8. Denoising loop
295
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
296
+
297
+ # 8.1 Apply denoising_end
298
+ if (
299
+ self.denoising_end is not None
300
+ and isinstance(self.denoising_end, float)
301
+ and self.denoising_end > 0
302
+ and self.denoising_end < 1
303
+ ):
304
+ discrete_timestep_cutoff = int(
305
+ round(
306
+ self.scheduler.config.num_train_timesteps
307
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
308
+ )
309
+ )
310
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
311
+ timesteps = timesteps[:num_inference_steps]
312
+
313
+ is_unet_compiled = is_compiled_module(self.unet)
314
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
315
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
316
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
317
+ for i, t in enumerate(timesteps):
318
+ # Relevant thread:
319
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
320
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
321
+ torch._inductor.cudagraph_mark_step_begin()
322
+ # expand the latents if we are doing classifier free guidance
323
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
324
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
325
+
326
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
327
+
328
+ # controlnet(s) inference
329
+ if guess_mode and self.do_classifier_free_guidance:
330
+ # Infer ControlNet only for the conditional batch.
331
+ control_model_input = latents
332
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
333
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
334
+ controlnet_added_cond_kwargs = {
335
+ "text_embeds": add_text_embeds.chunk(2)[1],
336
+ "time_ids": add_time_ids.chunk(2)[1],
337
+ }
338
+ else:
339
+ control_model_input = latent_model_input
340
+ controlnet_prompt_embeds = prompt_embeds
341
+ controlnet_added_cond_kwargs = added_cond_kwargs
342
+
343
+ if isinstance(controlnet_keep[i], list):
344
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
345
+ else:
346
+ controlnet_cond_scale = controlnet_conditioning_scale
347
+ if isinstance(controlnet_cond_scale, list):
348
+ controlnet_cond_scale = controlnet_cond_scale[0]
349
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
350
+ if i < len(timesteps) * (1 - id_injection_ratio):
351
+ token_length = 77
352
+ else:
353
+ token_length = 1000000
354
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
355
+ control_model_input,
356
+ t,
357
+ encoder_hidden_states=controlnet_prompt_embeds[:,:token_length],
358
+ controlnet_cond=image,
359
+ conditioning_scale=cond_scale,
360
+ guess_mode=guess_mode,
361
+ added_cond_kwargs=controlnet_added_cond_kwargs,
362
+ return_dict=False,
363
+ )
364
+
365
+ if guess_mode and self.do_classifier_free_guidance:
366
+ # Inferred ControlNet only for the conditional batch.
367
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
368
+ # add 0 to the unconditional batch to keep it unchanged.
369
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
370
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
371
+
372
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
373
+ added_cond_kwargs["image_embeds"] = image_embeds
374
+
375
+ # predict the noise residual
376
+ noise_pred = self.unet(
377
+ latent_model_input,
378
+ t,
379
+ encoder_hidden_states=prompt_embeds[:,:token_length],
380
+ timestep_cond=timestep_cond,
381
+ cross_attention_kwargs=self.cross_attention_kwargs,
382
+ down_block_additional_residuals=down_block_res_samples,
383
+ mid_block_additional_residual=mid_block_res_sample,
384
+ added_cond_kwargs=added_cond_kwargs,
385
+ return_dict=False,
386
+ )[0]
387
+
388
+ # perform guidance
389
+ if self.do_classifier_free_guidance:
390
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
391
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
392
+
393
+ # compute the previous noisy sample x_t -> x_t-1
394
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
395
+
396
+ if callback_on_step_end is not None:
397
+ callback_kwargs = {}
398
+ for k in callback_on_step_end_tensor_inputs:
399
+ callback_kwargs[k] = locals()[k]
400
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
401
+
402
+ latents = callback_outputs.pop("latents", latents)
403
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
404
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
405
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
406
+ negative_pooled_prompt_embeds = callback_outputs.pop(
407
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
408
+ )
409
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
410
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
411
+
412
+ # call the callback, if provided
413
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
414
+ progress_bar.update()
415
+ if callback is not None and i % callback_steps == 0:
416
+ step_idx = i // getattr(self.scheduler, "order", 1)
417
+ callback(step_idx, t, latents)
418
+
419
+ if not output_type == "latent":
420
+ # make sure the VAE is in float32 mode, as it overflows in float16
421
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
422
+
423
+ if needs_upcasting:
424
+ self.upcast_vae()
425
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
426
+
427
+ # unscale/denormalize the latents
428
+ # denormalize with the mean and std if available and not None
429
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
430
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
431
+ if has_latents_mean and has_latents_std:
432
+ latents_mean = (
433
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
434
+ )
435
+ latents_std = (
436
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
437
+ )
438
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
439
+ else:
440
+ latents = latents / self.vae.config.scaling_factor
441
+
442
+ image = self.vae.decode(latents, return_dict=False)[0]
443
+
444
+ # cast back to fp16 if needed
445
+ if needs_upcasting:
446
+ self.vae.to(dtype=torch.float16)
447
+ else:
448
+ image = latents
449
+
450
+ if not output_type == "latent":
451
+ # apply watermark if available
452
+ if self.watermark is not None:
453
+ image = self.watermark.apply_watermark(image)
454
+
455
+ image = self.image_processor.postprocess(image, output_type=output_type)
456
+
457
+ # Offload all models
458
+ self.maybe_free_model_hooks()
459
+
460
+ if not return_dict:
461
+ return (image,)
462
+
463
+ return StableDiffusionXLPipelineOutput(images=image)
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.34.2
2
+ diffusers==0.30.3
3
+ facexlib==0.3.0
4
+ gradio==5.23.1
5
+ gradio_client==1.8.0
6
+ httpcore==1.0.7
7
+ httpx==0.28.1
8
+ huggingface-hub==0.28.1
9
+ insightface==0.7.3
10
+ mtcnn==0.1.1
11
+ numpy==1.26.4
12
+ onnxruntime==1.19.2
13
+ opencv-python==4.8.0.74
14
+ pillow==10.4.0
15
+ pillow-avif-plugin==1.5.0
16
+ pillow-heif==0.21.0
17
+ sentencepiece==0.2.0
18
+ rtmlib==0.0.13
19
+ tensorflow==2.17.0
20
+ torch==2.1.2
21
+ transformers==4.44.2
utils/__init__.py ADDED
File without changes
utils/draw_condition.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab
2
+ # Copyright (c) 2024 Bytedance Ltd. and/or its affiliates
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # This file has been modified by Bytedance Ltd. and/or its affiliates on October 10, 2024.
6
+ #
7
+ # Original file was released under Apache License 2.0, with the full license text
8
+ # available at https://github.com/open-mmlab/mmpose/blob/main/LICENSE.
9
+ #
10
+ # This modified file is released under the same license.
11
+
12
+
13
+ import numpy as np
14
+ import cv2
15
+ from itertools import product
16
+ import math
17
+
18
+ def draw_openpose_from_mmpose(canvas, keypoints, keypoint_scores, kpt_thr=0.3, ignore_individual_points=False):
19
+ """
20
+ canvas: background image
21
+ keypoints: N x 17 x 2
22
+ keypoint_scores: N x 17
23
+ ret: RGB order (note: although we use cv2 to process image, result is in RGB order)
24
+ """
25
+
26
+ # openpose format
27
+ limb_seq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
28
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],
29
+ [1, 16], [16, 18]]
30
+
31
+ colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0],
32
+ [85, 255, 0], [0, 255, 0], [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255],
33
+ [0, 85, 255], [0, 0, 255], [85, 0, 255], [170, 0, 255], [255, 0, 255],
34
+ [255, 0, 170], [255, 0, 85]]
35
+
36
+ stickwidth = 4
37
+ num_openpose_kpt = 18
38
+ num_link = len(limb_seq)
39
+
40
+ # concatenate scores and keypoints
41
+ keypoints = np.concatenate((keypoints, keypoint_scores.reshape(-1, 17, 1)), axis=-1)
42
+
43
+ # compute neck joint
44
+ neck = (keypoints[:, 5] + keypoints[:, 6]) / 2
45
+ #if keypoints[:, 5, 2] < kpt_thr or keypoints[:, 6, 2] < kpt_thr:
46
+ # neck[:, 2] = 0
47
+ neck[:, 2] = np.minimum(keypoints[:, 5, 2], keypoints[:, 6, 2])
48
+
49
+ # 17 keypoints to 18 keypoints
50
+ new_keypoints = np.insert(keypoints[:, ], 17, neck, axis=1)
51
+
52
+ # mmpose format to openpose format
53
+ openpose_idx = [15, 14, 17, 16, 2, 6, 3, 7, 4, 8, 12, 9, 13, 10, 1]
54
+ mmpose_idx = [1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17]
55
+ new_keypoints[:, openpose_idx, :] = new_keypoints[:, mmpose_idx, :]
56
+
57
+ black_img = canvas
58
+ num_instance = new_keypoints.shape[0]
59
+
60
+ # drw keypoints
61
+ for i in range(num_instance):
62
+ valid = [False] * 18
63
+ for link_idx in range(num_link):
64
+ conf = new_keypoints[i][np.array(limb_seq[link_idx]) - 1, 2]
65
+ if np.sum(conf > kpt_thr) == 2:
66
+ valid[limb_seq[link_idx][0]-1] = True
67
+ valid[limb_seq[link_idx][1]-1] = True
68
+ for j in range(num_openpose_kpt):
69
+ x, y, conf = new_keypoints[i][j]
70
+ if conf > kpt_thr and valid[j]:
71
+ cv2.circle(black_img, (int(x), int(y)), 4, colors[j], thickness=-1)
72
+
73
+ # draw links
74
+ cur_black_img = black_img.copy()
75
+ for i, link_idx in product(range(num_instance), range(num_link)):
76
+ conf = new_keypoints[i][np.array(limb_seq[link_idx]) - 1, 2]
77
+ if np.sum(conf > kpt_thr) == 2:
78
+ Y = new_keypoints[i][np.array(limb_seq[link_idx]) - 1, 0]
79
+ X = new_keypoints[i][np.array(limb_seq[link_idx]) - 1, 1]
80
+ mX = np.mean(X)
81
+ mY = np.mean(Y)
82
+ length = ((X[0] - X[1])**2 + (Y[0] - Y[1])**2)**0.5
83
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
84
+ polygon = cv2.ellipse2Poly(
85
+ (int(mY), int(mX)), (int(length / 2), stickwidth), int(angle),
86
+ 0, 360, 1)
87
+ cv2.fillConvexPoly(cur_black_img, polygon, colors[link_idx])
88
+ black_img = cv2.addWeighted(black_img, 0.4, cur_black_img, 0.6, 0)
89
+
90
+ return black_img