EndlessSora commited on
Commit
df5230f
·
1 Parent(s): d0fff1f

update demo & README.md

Browse files
.gitignore ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ .idea
3
+ .ipynb_checkpoints
4
+ .gradio
5
+ *.swp
6
+ *.pyc
7
+ __pycache__
8
+ *.tar*
9
+ *.zip
10
+ *.pkl
11
+ *.pyc
12
+ *.bak
13
+ *.png
14
+ *.deb
15
+
16
+ .isort.cfg
17
+ .pre-commit-config.yaml
18
+
19
+ dataset_stats
20
+ debug*
21
+ locks
22
+ checkpoints
23
+ pretrained_checkpoint
24
+ ./models
25
+ models
26
+ results
27
+ wandb
28
+ tmp*
29
+ env*
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: InfiniteUFlux
3
- emoji: 😻
4
- colorFrom: indigo
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 5.18.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
- short_description: Infinite You Flux demo
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
1
  ---
2
+ title: InfiniteYou-FLUX
3
+ emoji: 📸
4
+ colorFrom: red
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 5.21.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
+ short_description: Flexible Photo Recrafting While Preserving Your Identity
12
  ---
13
 
14
+ Some images in this demo are from public domains or generated by 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 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. Users are granted the freedom to create images using this tool, but they must comply with local laws and use it responsibly. The developers do not assume any responsibility for potential misuse by users.
app.py CHANGED
@@ -1,7 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
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 gradio as gr
16
+ import pillow_avif
17
+ import spaces
18
+ import torch
19
+ from huggingface_hub import snapshot_download
20
+ from pillow_heif import register_heif_opener
21
+
22
+ from pipelines.pipeline_infu_flux import InfUFluxPipeline
23
+
24
+
25
+ # Register HEIF support for Pillow
26
+ register_heif_opener()
27
+
28
+ class ModelVersion:
29
+ STAGE_1 = "sim_stage1"
30
+ STAGE_2 = "aes_stage2"
31
+
32
+ DEFAULT_VERSION = STAGE_2
33
+
34
+ ENABLE_ANTI_BLUR_DEFAULT = False
35
+ ENABLE_REALISM_DEFAULT = False
36
+
37
+ pipeline = None
38
+ loaded_pipeline_config = {
39
+ "model_version": "aes_stage2",
40
+ "enable_realism": False,
41
+ "enable_anti_blur": False,
42
+ }
43
+
44
+
45
+ def download_models():
46
+ snapshot_download(repo_id='ByteDance/InfiniteYou', local_dir='./models/InfiniteYou', local_dir_use_symlinks=False)
47
+ try:
48
+ snapshot_download(repo_id='black-forest-labs/FLUX.1-dev', local_dir='./models/FLUX.1-dev', local_dir_use_symlinks=False)
49
+ except Exception as e:
50
+ print(e)
51
+ print('\nYou are downloading `black-forest-labs/FLUX.1-dev` to `./models/FLUX.1-dev` but failed. '
52
+ 'Please accept the agreement and obtain access at https://huggingface.co/black-forest-labs/FLUX.1-dev. '
53
+ 'Then, use `huggingface-cli login` and your access tokens at https://huggingface.co/settings/tokens to authenticate. '
54
+ 'After that, run the code again.')
55
+ print('\nYou can also download it manually from HuggingFace and put it in `./models/InfiniteYou`, '
56
+ 'or you can modify `base_model_path` in `app.py` to specify the correct path.')
57
+ exit()
58
+
59
+
60
+ def prepare_pipeline(model_version, enable_realism, enable_anti_blur):
61
+ global pipeline
62
+
63
+ if (
64
+ pipeline
65
+ and loaded_pipeline_config["enable_realism"] == enable_realism
66
+ and loaded_pipeline_config["enable_anti_blur"] == enable_anti_blur
67
+ and model_version == loaded_pipeline_config["model_version"]
68
+ ):
69
+ return
70
+
71
+ loaded_pipeline_config["enable_realism"] = enable_realism
72
+ loaded_pipeline_config["enable_anti_blur"] = enable_anti_blur
73
+ loaded_pipeline_config["model_version"] = model_version
74
+
75
+ if pipeline is None or pipeline.model_version != model_version:
76
+ del pipeline
77
+
78
+ model_path = f'./models/InfiniteYou/infu_flux_v1.0/{model_version}'
79
+ print(f'loading model from {model_path}')
80
+
81
+ pipeline = InfUFluxPipeline(
82
+ base_model_path='./models/FLUX.1-dev',
83
+ infu_model_path=model_path,
84
+ insightface_root_path='./models/InfiniteYou/supports/insightface',
85
+ image_proj_num_tokens=8,
86
+ infu_flux_version='v1.0',
87
+ model_version=model_version,
88
+ )
89
+
90
+ pipeline.pipe.delete_adapters(['realism', 'anti_blur'])
91
+ loras = []
92
+ if enable_realism:
93
+ loras.append(['./models/InfiniteYou/supports/optional_loras/flux_realism_lora.safetensors', 'realism', 1.0])
94
+ if enable_anti_blur:
95
+ loras.append(['./models/InfiniteYou/supports/optional_loras/flux_anti_blur_lora.safetensors', 'anti_blur', 1.0])
96
+ pipeline.load_loras(loras)
97
+
98
+
99
+ @spaces.GPU
100
+ def generate_image(
101
+ input_image,
102
+ control_image,
103
+ prompt,
104
+ seed,
105
+ width,
106
+ height,
107
+ guidance_scale,
108
+ num_steps,
109
+ infusenet_conditioning_scale,
110
+ infusenet_guidance_start,
111
+ infusenet_guidance_end,
112
+ enable_realism,
113
+ enable_anti_blur,
114
+ model_version
115
+ ):
116
+ global pipeline
117
+
118
+ prepare_pipeline(model_version=model_version, enable_realism=enable_realism, enable_anti_blur=enable_anti_blur)
119
+
120
+ if seed == 0:
121
+ seed = torch.seed() & 0xFFFFFFFF
122
+
123
+ try:
124
+ image = pipeline(
125
+ id_image=input_image,
126
+ prompt=prompt,
127
+ control_image=control_image,
128
+ seed=seed,
129
+ width=width,
130
+ height=height,
131
+ guidance_scale=guidance_scale,
132
+ num_steps=num_steps,
133
+ infusenet_conditioning_scale=infusenet_conditioning_scale,
134
+ infusenet_guidance_start=infusenet_guidance_start,
135
+ infusenet_guidance_end=infusenet_guidance_end,
136
+ )
137
+ except Exception as e:
138
+ print(e)
139
+ gr.Error(f"An error occurred: {e}")
140
+ return gr.update()
141
+
142
+ return gr.update(value = image, label=f"Generated image, seed = {seed}")
143
+
144
+
145
+ def generate_examples(id_image, control_image, prompt_text, seed, enable_realism, enable_anti_blur, model_version):
146
+ return generate_image(id_image, control_image, prompt_text, seed, 864, 1152, 3.5, 30, 1.0, 0.0, 1.0, enable_realism, enable_anti_blur, model_version)
147
+
148
+
149
+ sample_list = [
150
+ ['./assets/examples/yann-lecun_resize.jpg', None, 'A sophisticated gentleman exuding confidence. He is dressed in a 1990s brown plaid jacket with a high collar, paired with a dark grey turtleneck. His trousers are tailored and charcoal in color, complemented by a sleek leather belt. The background showcases an elegant library with bookshelves, a marble fireplace, and warm lighting, creating a refined and cozy atmosphere. His relaxed posture and casual hand-in-pocket stance add to his composed and stylish demeanor', 666, False, False, 'aes_stage2'],
151
+ ['./assets/examples/yann-lecun_resize.jpg', './assets/examples/man_pose.jpg', 'A man, portrait, cinematic', 42, True, False, 'aes_stage2'],
152
+ ['./assets/examples/yann-lecun_resize.jpg', './assets/examples/yann-lecun_resize.jpg', 'A man, portrait, cinematic', 12345, False, False, 'sim_stage1'],
153
+ ['./assets/examples/yangmi.jpg', None, 'A woman, portrait, cinematic', 1621695706, False, False, 'sim_stage1'],
154
+ ['./assets/examples/yangmi.jpg', None, 'A young woman holding a sign with the text "InfiniteYou", "Infinite" in black and "You" in red, pure background', 3724009366, False, False, 'aes_stage2'],
155
+ ['./assets/examples/yangmi.jpg', None, 'A photo of an elegant Javanese bride in traditional attire, with long hair styled into intricate a braid made of many fresh flowers, wearing a delicate headdress made from sequins and beads. She\'s holding flowers, light smiling at the camera, against a backdrop adorned with orchid blooms. The scene captures her grace as she stands amidst soft pastel colors, adding to its dreamy atmosphere', 42, True, False, 'aes_stage2'],
156
+ ['./assets/examples/yangmi.jpg', None, 'A photo of an elegant Javanese bride in traditional attire, with long hair styled into intricate a braid made of many fresh flowers, wearing a delicate headdress made from sequins and beads. She\'s holding flowers, light smiling at the camera, against a backdrop adorned with orchid blooms. The scene captures her grace as she stands amidst soft pastel colors, adding to its dreamy atmosphere', 42, False, False, 'sim_stage1'],
157
+ ]
158
+
159
+ with gr.Blocks() as demo:
160
+ session_state = gr.State({})
161
+ default_model_version = "v1.0"
162
+
163
+ gr.Markdown("""
164
+ <div style="text-align: center; max-width: 900px; margin: 0 auto;">
165
+ <h1 style="font-size: 1.5rem; font-weight: 700; display: block;">InfiniteYou-FLUX</h1>
166
+ <h2 style="font-size: 1.2rem; font-weight: 300; margin-bottom: 1rem; display: block;">Official Gradio Demo for <a href="https://arxiv.org/abs/2503.xxxxx">InfiniteYou: Flexible Photo Recrafting While Preserving Your Identity</a></h2>
167
+ <a href="https://bytedance.github.io/InfiniteYou">[Project Page]</a>&ensp;
168
+ <a href="https://arxiv.org/abs/2503.xxxxx">[Paper]</a>&ensp;
169
+ <a href="https://github.com/bytedance/InfiniteYou">[Code]</a>&ensp;
170
+ <a href="https://huggingface.co/ByteDance/InfiniteYou">[Model]</a>
171
+ </div>
172
+
173
+ ### 💡 How to Use This Demo:
174
+ 1. **Upload an identity (ID) image containing a human face.** For images with multiple faces, only the largest face will be detected. The face should ideally be clear and large enough, without significant occlusions or blur.
175
+ 2. **Enter the text prompt to describe the generated image and select the model version.** Please refer to **important usage tips** under the Generated Image field.
176
+ 3. *[Optional] Upload a control image containing a human face.* Only five facial keypoints will be extracted to control the generation. If not provided, we use a black control image, indicating no control.
177
+ 4. *[Optional] Adjust advanced hyperparameters or apply optional LoRAs to meet personal needs.* Please refer to **important usage tips** under the Generated Image field.
178
+ 5. **Click the "Generate" button to generate an image.** Enjoy!
179
+ """)
180
+
181
+ with gr.Row():
182
+ with gr.Column(scale=3):
183
+ with gr.Row():
184
+ ui_id_image = gr.Image(label="Identity Image", type="pil", scale=3, height=370, min_width=100)
185
+
186
+ with gr.Column(scale=2, min_width=100):
187
+ ui_control_image = gr.Image(label="Control Image [Optional]", type="pil", height=370, min_width=100)
188
+
189
+ ui_prompt_text = gr.Textbox(label="Prompt", value="Portrait, 4K, high quality, cinematic")
190
+ ui_model_version = gr.Dropdown(
191
+ label="Model Version",
192
+ choices=[ModelVersion.STAGE_1, ModelVersion.STAGE_2],
193
+ value=ModelVersion.DEFAULT_VERSION,
194
+ )
195
+
196
+ ui_btn_generate = gr.Button("Generate")
197
+ with gr.Accordion("Advanced", open=False):
198
+ with gr.Row():
199
+ ui_num_steps = gr.Number(label="num steps", value=30)
200
+ ui_seed = gr.Number(label="seed (0 for random)", value=0)
201
+ with gr.Row():
202
+ ui_width = gr.Number(label="width", value=864)
203
+ ui_height = gr.Number(label="height", value=1152)
204
+ ui_guidance_scale = gr.Number(label="guidance scale", value=3.5, step=0.5)
205
+ ui_infusenet_conditioning_scale = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="infusenet conditioning scale")
206
+ with gr.Row():
207
+ ui_infusenet_guidance_start = gr.Slider(minimum=0.0, maximum=1.0, value=0.0, step=0.05, label="infusenet guidance start")
208
+ ui_infusenet_guidance_end = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="infusenet guidance end")
209
+
210
+ with gr.Accordion("LoRAs [Optional]", open=True):
211
+ with gr.Row():
212
+ ui_enable_realism = gr.Checkbox(label="Enable realism LoRA", value=ENABLE_REALISM_DEFAULT)
213
+ ui_enable_anti_blur = gr.Checkbox(label="Enable anti-blur LoRA", value=ENABLE_ANTI_BLUR_DEFAULT)
214
+
215
+ with gr.Column(scale=2):
216
+ image_output = gr.Image(label="Generated Image", interactive=False, height=550, format='png')
217
+ gr.Markdown(
218
+ """
219
+ ### ❗️ Important Usage Tips:
220
+ - **Model Version**: `aes_stage2` is used by default for better text-image alignment and aesthetics. For higher ID similarity, please try `sim_stage1`.
221
+ - **Useful Hyperparameters**: Usually, there is NO need to adjust too much. If necessary, try a slightly larger `--infusenet_guidance_start` (*e.g.*, `0.1`) only (especially helpful for `sim_stage1`). If still not satisfactory, then try a slightly smaller `--infusenet_conditioning_scale` (*e.g.*, `0.9`).
222
+ - **Optional LoRAs**: `realism` and `anti-blur`. To enable them, please check the corresponding boxes. They are optional and were NOT used in our paper.
223
+ - **Gender Prompt**: If the generated gender is not preferred, add specific words in the text prompt, such as 'a man', 'a woman', *etc*. We encourage using inclusive and respectful language.
224
+ """
225
+ )
226
+
227
+ gr.Examples(
228
+ sample_list,
229
+ inputs=[ui_id_image, ui_control_image, ui_prompt_text, ui_seed, ui_enable_realism, ui_enable_anti_blur, ui_model_version],
230
+ outputs=[image_output],
231
+ fn=generate_examples,
232
+ cache_examples=True,
233
+ )
234
+
235
+ ui_btn_generate.click(
236
+ generate_image,
237
+ inputs=[
238
+ ui_id_image,
239
+ ui_control_image,
240
+ ui_prompt_text,
241
+ ui_seed,
242
+ ui_width,
243
+ ui_height,
244
+ ui_guidance_scale,
245
+ ui_num_steps,
246
+ ui_infusenet_conditioning_scale,
247
+ ui_infusenet_guidance_start,
248
+ ui_infusenet_guidance_end,
249
+ ui_enable_realism,
250
+ ui_enable_anti_blur,
251
+ ui_model_version
252
+ ],
253
+ outputs=[image_output],
254
+ concurrency_id="gpu"
255
+ )
256
+
257
+ with gr.Accordion("Local Gradio Demo for Developers", open=False):
258
+ gr.Markdown(
259
+ 'Please refer to our GitHub repository to [run the InfiniteYou-FLUX gradio demo locally](https://github.com/bytedance/InfiniteYou#local-gradio-demo).'
260
+ )
261
+
262
+ gr.Markdown(
263
+ """
264
+ ---
265
+ ### 📜 Disclaimer and Licenses
266
+ Some images in this demo are from public domains or generated by 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.
267
+
268
+ The use of the released code, model, and demo must strictly adhere to the respective licenses. Our code is released under the Apache 2.0 License, and our model is released under the Creative Commons Attribution-NonCommercial 4.0 International Public License 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, etc., must follow their original licenses and be used only for academic research purposes.
269
+
270
+ This research aims to positively impact the Generative AI field. Users are granted freedom to create images using this tool, but they must comply with local laws and use it responsibly. The developers do not assume any responsibility for potential misuse.
271
+
272
+ ### 📖 Citation
273
+
274
+ If you find InfiniteYou useful for your research or applications, please cite our paper:
275
+
276
+ ```bibtex
277
+ @article{jiang2025infiniteyou,
278
+ title={{InfiniteYou}: Flexible Photo Recrafting While Preserving Your Identity},
279
+ author={Jiang, Liming and Yan, Qing and Jia, Yumin and Liu, Zichuan and Kang, Hao and Lu, Xin},
280
+ journal={arXiv preprint},
281
+ volume={arXiv:2503.xxxxx},
282
+ year={2025}
283
+ }
284
+ ```
285
+
286
+ We also appreciate it if you could give a star ⭐ to our [Github repository](https://github.com/bytedance/InfiniteYou). Thanks a lot!
287
+ """
288
+ )
289
+
290
+ download_models()
291
 
292
+ prepare_pipeline(model_version=ModelVersion.DEFAULT_VERSION, enable_realism=ENABLE_REALISM_DEFAULT, enable_anti_blur=ENABLE_ANTI_BLUR_DEFAULT)
 
293
 
294
+ demo.queue()
295
+ demo.launch(server_name='0.0.0.0') # IPv4
296
+ # demo.launch(server_name='[::]') # IPv6
assets/examples/man_pose.jpg ADDED
assets/examples/yangmi.jpg ADDED
assets/examples/yann-lecun_resize.jpg ADDED
pipelines/__init__.py ADDED
File without changes
pipelines/pipeline_flux_infusenet.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 Bytedance Ltd. and/or its affiliates.
2
+ # Copyright (c) 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from diffusers import FluxControlNetPipeline
22
+ from diffusers.models.controlnet_flux import FluxControlNetModel, FluxMultiControlNetModel
23
+ from diffusers.image_processor import PipelineImageInput
24
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
25
+ from diffusers.utils import replace_example_docstring, is_torch_xla_available, logging
26
+
27
+
28
+ if is_torch_xla_available():
29
+ import torch_xla.core.xla_model as xm
30
+
31
+ XLA_AVAILABLE = True
32
+ else:
33
+ XLA_AVAILABLE = False
34
+
35
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
+
37
+
38
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
39
+ def calculate_shift(
40
+ image_seq_len,
41
+ base_seq_len: int = 256,
42
+ max_seq_len: int = 4096,
43
+ base_shift: float = 0.5,
44
+ max_shift: float = 1.16,
45
+ ):
46
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
47
+ b = base_shift - m * base_seq_len
48
+ mu = image_seq_len * m + b
49
+ return mu
50
+
51
+
52
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
53
+ def retrieve_timesteps(
54
+ scheduler,
55
+ num_inference_steps: Optional[int] = None,
56
+ device: Optional[Union[str, torch.device]] = None,
57
+ timesteps: Optional[List[int]] = None,
58
+ sigmas: Optional[List[float]] = None,
59
+ **kwargs,
60
+ ):
61
+ r"""
62
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
63
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
64
+
65
+ Args:
66
+ scheduler (`SchedulerMixin`):
67
+ The scheduler to get timesteps from.
68
+ num_inference_steps (`int`):
69
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
70
+ must be `None`.
71
+ device (`str` or `torch.device`, *optional*):
72
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
73
+ timesteps (`List[int]`, *optional*):
74
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
75
+ `num_inference_steps` and `sigmas` must be `None`.
76
+ sigmas (`List[float]`, *optional*):
77
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
78
+ `num_inference_steps` and `timesteps` must be `None`.
79
+
80
+ Returns:
81
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
82
+ second element is the number of inference steps.
83
+ """
84
+ if timesteps is not None and sigmas is not None:
85
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
86
+ if timesteps is not None:
87
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
88
+ if not accepts_timesteps:
89
+ raise ValueError(
90
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
91
+ f" timestep schedules. Please check whether you are using the correct scheduler."
92
+ )
93
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
94
+ timesteps = scheduler.timesteps
95
+ num_inference_steps = len(timesteps)
96
+ elif sigmas is not None:
97
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
98
+ if not accept_sigmas:
99
+ raise ValueError(
100
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
101
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
102
+ )
103
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
104
+ timesteps = scheduler.timesteps
105
+ num_inference_steps = len(timesteps)
106
+ else:
107
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
108
+ timesteps = scheduler.timesteps
109
+ return timesteps, num_inference_steps
110
+
111
+
112
+ class FluxInfuseNetPipeline(FluxControlNetPipeline):
113
+ @torch.no_grad()
114
+ def __call__(
115
+ self,
116
+ prompt: Union[str, List[str]] = None,
117
+ prompt_2: Optional[Union[str, List[str]]] = None,
118
+ height: Optional[int] = None,
119
+ width: Optional[int] = None,
120
+ num_inference_steps: int = 28,
121
+ timesteps: List[int] = None,
122
+ guidance_scale: float = 3.5,
123
+ controlnet_guidance_scale: float = 1.0,
124
+ control_guidance_start: Union[float, List[float]] = 0.0,
125
+ control_guidance_end: Union[float, List[float]] = 1.0,
126
+ control_image: PipelineImageInput = None,
127
+ control_mode: Optional[Union[int, List[int]]] = None,
128
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
129
+ num_images_per_prompt: Optional[int] = 1,
130
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
131
+ latents: Optional[torch.FloatTensor] = None,
132
+ prompt_embeds: Optional[torch.FloatTensor] = None,
133
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
134
+ output_type: Optional[str] = "pil",
135
+ return_dict: bool = True,
136
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
137
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
138
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
139
+ max_sequence_length: int = 512,
140
+
141
+ # ID-specific parameters
142
+ controlnet_prompt_embeds: Optional[torch.FloatTensor] = None,
143
+
144
+ # True CFG parameters
145
+ true_guidance_scale: float = 1.0,
146
+ negative_prompt: Optional[Union[str, List[str]]] = None,
147
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
148
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
149
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
150
+ ):
151
+ r"""
152
+ Function invoked when calling the pipeline for generation.
153
+
154
+ Args:
155
+ prompt (`str` or `List[str]`, *optional*):
156
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
157
+ instead.
158
+ prompt_2 (`str` or `List[str]`, *optional*):
159
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
160
+ will be used instead
161
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
162
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
163
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
164
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
165
+ num_inference_steps (`int`, *optional*, defaults to 50):
166
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
167
+ expense of slower inference.
168
+ timesteps (`List[int]`, *optional*):
169
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
170
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
171
+ passed will be used. Must be in descending order.
172
+ guidance_scale (`float`, *optional*, defaults to 7.0):
173
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
174
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
175
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
176
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
177
+ usually at the expense of lower image quality.
178
+ controlnet_guidance_scale (`float`, *optional*, defaults to 7.0):
179
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
180
+ `controlnet_guidance_scale` is defined as `w` of equation 2. of [Imagen
181
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
182
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
183
+ usually at the expense of lower image quality.
184
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
185
+ The percentage of total steps at which the ControlNet starts applying.
186
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
187
+ The percentage of total steps at which the ControlNet stops applying.
188
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
189
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
190
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
191
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
192
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
193
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
194
+ images must be passed as a list such that each element of the list can be correctly batched for input
195
+ to a single ControlNet.
196
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
197
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
198
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
199
+ the corresponding scale as a list.
200
+ control_mode (`int` or `List[int]`,, *optional*, defaults to None):
201
+ The control mode when applying ControlNet-Union.
202
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
203
+ The number of images to generate per prompt.
204
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
205
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
206
+ to make generation deterministic.
207
+ latents (`torch.FloatTensor`, *optional*):
208
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
209
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
210
+ tensor will ge generated by sampling using the supplied random `generator`.
211
+ prompt_embeds (`torch.FloatTensor`, *optional*):
212
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
213
+ provided, text embeddings will be generated from `prompt` input argument.
214
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
215
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
216
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
217
+ output_type (`str`, *optional*, defaults to `"pil"`):
218
+ The output format of the generate image. Choose between
219
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
220
+ return_dict (`bool`, *optional*, defaults to `True`):
221
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
222
+ joint_attention_kwargs (`dict`, *optional*):
223
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
224
+ `self.processor` in
225
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
226
+ callback_on_step_end (`Callable`, *optional*):
227
+ A function that calls at the end of each denoising steps during the inference. The function is called
228
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
229
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
230
+ `callback_on_step_end_tensor_inputs`.
231
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
232
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
233
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
234
+ `._callback_tensor_inputs` attribute of your pipeline class.
235
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
236
+ controlnet_prompt_embeds (`torch.FloatTensor`, *optional*):
237
+ Pre-generated embeddings for the InfuseNet. Can be used to easily tweak inputs, *e.g.* image embeddings.
238
+ If not provided, embeddings will be generated from `prompt` or `prompt_embeds` input arguments.
239
+ true_guidance_scale (`float`, *optional*, defaults to 1.0):
240
+ True CFG scale as defined in [Classifier-Free Diffusion Guidance]((https://arxiv.org/abs/2207.12598).
241
+ negative_prompt (`str` or `List[str]`, *optional*):
242
+ The negative prompt or negative prompts to guide the image generation. If not defined, one has to pass
243
+ `negative_prompt_embeds`. instead.
244
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
245
+ The negative prompt or negative prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined,
246
+ `negative_prompt` is will be used instead.
247
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
248
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
249
+ weighting. If not provided, negative text embeddings will be generated from `negative_prompt` input
250
+ argument.
251
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
252
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
253
+ weighting. If not provided, negative pooled text embeddings will be generated from
254
+ `negative_prompt` input argument.
255
+
256
+ Examples:
257
+
258
+ Returns:
259
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
260
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
261
+ images.
262
+ """
263
+
264
+ height = height or self.default_sample_size * self.vae_scale_factor
265
+ width = width or self.default_sample_size * self.vae_scale_factor
266
+
267
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
268
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
269
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
270
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
271
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
272
+ mult = len(self.controlnet.nets) if isinstance(self.controlnet, FluxMultiControlNetModel) else 1
273
+ control_guidance_start, control_guidance_end = (
274
+ mult * [control_guidance_start],
275
+ mult * [control_guidance_end],
276
+ )
277
+
278
+ # 1. Check inputs. Raise error if not correct
279
+ self.check_inputs(
280
+ prompt,
281
+ prompt_2,
282
+ height,
283
+ width,
284
+ prompt_embeds=prompt_embeds,
285
+ pooled_prompt_embeds=pooled_prompt_embeds,
286
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
287
+ max_sequence_length=max_sequence_length,
288
+ )
289
+
290
+ self._guidance_scale = guidance_scale
291
+ self._controlnet_guidance_scale = controlnet_guidance_scale
292
+ self._true_guidance_scale = true_guidance_scale
293
+ self._joint_attention_kwargs = joint_attention_kwargs
294
+ self._interrupt = False
295
+
296
+ # 2. Define call parameters
297
+ if prompt is not None and isinstance(prompt, str):
298
+ batch_size = 1
299
+ elif prompt is not None and isinstance(prompt, list):
300
+ batch_size = len(prompt)
301
+ else:
302
+ batch_size = prompt_embeds.shape[0]
303
+
304
+ device = self._execution_device
305
+ dtype = self.transformer.dtype
306
+
307
+ lora_scale = (
308
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
309
+ )
310
+ (
311
+ prompt_embeds,
312
+ pooled_prompt_embeds,
313
+ text_ids,
314
+ ) = self.encode_prompt(
315
+ prompt=prompt,
316
+ prompt_2=prompt_2,
317
+ prompt_embeds=prompt_embeds,
318
+ pooled_prompt_embeds=pooled_prompt_embeds,
319
+ device=device,
320
+ num_images_per_prompt=num_images_per_prompt,
321
+ max_sequence_length=max_sequence_length,
322
+ lora_scale=lora_scale,
323
+ )
324
+ if negative_prompt is not None or (negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None):
325
+ (
326
+ negative_prompt_embeds,
327
+ negative_pooled_prompt_embeds,
328
+ negative_text_ids,
329
+ ) = self.encode_prompt(
330
+ prompt=negative_prompt,
331
+ prompt_2=negative_prompt_2,
332
+ prompt_embeds=negative_prompt_embeds,
333
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
334
+ device=device,
335
+ num_images_per_prompt=num_images_per_prompt,
336
+ max_sequence_length=max_sequence_length,
337
+ lora_scale=lora_scale,
338
+ )
339
+
340
+ if controlnet_prompt_embeds is None:
341
+ controlnet_prompt_embeds = prompt_embeds
342
+ (
343
+ controlnet_prompt_embeds,
344
+ pooled_prompt_embeds,
345
+ controlnet_text_ids,
346
+ ) = self.encode_prompt(
347
+ prompt=prompt,
348
+ prompt_2=prompt_2,
349
+ prompt_embeds=controlnet_prompt_embeds,
350
+ pooled_prompt_embeds=pooled_prompt_embeds,
351
+ device=device,
352
+ num_images_per_prompt=num_images_per_prompt,
353
+ max_sequence_length=max_sequence_length,
354
+ lora_scale=lora_scale,
355
+ )
356
+
357
+ # 3. Prepare control image
358
+ num_channels_latents = self.transformer.config.in_channels // 4
359
+ if isinstance(self.controlnet, FluxControlNetModel):
360
+ control_image = self.prepare_image(
361
+ image=control_image,
362
+ width=width,
363
+ height=height,
364
+ batch_size=batch_size * num_images_per_prompt,
365
+ num_images_per_prompt=num_images_per_prompt,
366
+ device=device,
367
+ dtype=self.vae.dtype,
368
+ )
369
+ height, width = control_image.shape[-2:]
370
+
371
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
372
+ controlnet_blocks_repeat = False if self.controlnet.input_hint_block is None else True
373
+ if self.controlnet.input_hint_block is None:
374
+ # vae encode
375
+ control_image = self.vae.encode(control_image).latent_dist.sample()
376
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
377
+
378
+ # pack
379
+ height_control_image, width_control_image = control_image.shape[2:]
380
+ control_image = self._pack_latents(
381
+ control_image,
382
+ batch_size * num_images_per_prompt,
383
+ num_channels_latents,
384
+ height_control_image,
385
+ width_control_image,
386
+ )
387
+
388
+ # Here we ensure that `control_mode` has the same length as the control_image.
389
+ if control_mode is not None:
390
+ if not isinstance(control_mode, int):
391
+ raise ValueError(" For `FluxControlNet`, `control_mode` should be an `int` or `None`")
392
+ control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
393
+ control_mode = control_mode.view(-1, 1).expand(control_image.shape[0], 1)
394
+
395
+ elif isinstance(self.controlnet, FluxMultiControlNetModel):
396
+ control_images = []
397
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
398
+ controlnet_blocks_repeat = False if self.controlnet.nets[0].input_hint_block is None else True
399
+ for i, control_image_ in enumerate(control_image):
400
+ control_image_ = self.prepare_image(
401
+ image=control_image_,
402
+ width=width,
403
+ height=height,
404
+ batch_size=batch_size * num_images_per_prompt,
405
+ num_images_per_prompt=num_images_per_prompt,
406
+ device=device,
407
+ dtype=self.vae.dtype,
408
+ )
409
+ height, width = control_image_.shape[-2:]
410
+
411
+ if self.controlnet.nets[0].input_hint_block is None:
412
+ # vae encode
413
+ control_image_ = self.vae.encode(control_image_).latent_dist.sample()
414
+ control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
415
+
416
+ # pack
417
+ height_control_image, width_control_image = control_image_.shape[2:]
418
+ control_image_ = self._pack_latents(
419
+ control_image_,
420
+ batch_size * num_images_per_prompt,
421
+ num_channels_latents,
422
+ height_control_image,
423
+ width_control_image,
424
+ )
425
+ control_images.append(control_image_)
426
+
427
+ control_image = control_images
428
+
429
+ # Here we ensure that `control_mode` has the same length as the control_image.
430
+ if isinstance(control_mode, list) and len(control_mode) != len(control_image):
431
+ raise ValueError(
432
+ "For Multi-ControlNet, `control_mode` must be a list of the same "
433
+ + " length as the number of controlnets (control images) specified"
434
+ )
435
+ if not isinstance(control_mode, list):
436
+ control_mode = [control_mode] * len(control_image)
437
+ # set control mode
438
+ control_modes = []
439
+ for cmode in control_mode:
440
+ if cmode is None:
441
+ cmode = -1
442
+ control_mode = torch.tensor(cmode).expand(control_images[0].shape[0]).to(device, dtype=torch.long)
443
+ control_modes.append(control_mode)
444
+ control_mode = control_modes
445
+
446
+ # 4. Prepare latent variables
447
+ num_channels_latents = self.transformer.config.in_channels // 4
448
+ latents, latent_image_ids = self.prepare_latents(
449
+ batch_size * num_images_per_prompt,
450
+ num_channels_latents,
451
+ height,
452
+ width,
453
+ prompt_embeds.dtype,
454
+ device,
455
+ generator,
456
+ latents,
457
+ )
458
+
459
+ # 5. Prepare timesteps
460
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
461
+ image_seq_len = latents.shape[1]
462
+ mu = calculate_shift(
463
+ image_seq_len,
464
+ self.scheduler.config.base_image_seq_len,
465
+ self.scheduler.config.max_image_seq_len,
466
+ self.scheduler.config.base_shift,
467
+ self.scheduler.config.max_shift,
468
+ )
469
+ timesteps, num_inference_steps = retrieve_timesteps(
470
+ self.scheduler,
471
+ num_inference_steps,
472
+ device,
473
+ timesteps,
474
+ sigmas,
475
+ mu=mu,
476
+ )
477
+
478
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
479
+ self._num_timesteps = len(timesteps)
480
+
481
+ # 6. Create tensor stating which controlnets to keep
482
+ controlnet_keep = []
483
+ for i in range(len(timesteps)):
484
+ keeps = [
485
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
486
+ for s, e in zip(control_guidance_start, control_guidance_end)
487
+ ]
488
+ controlnet_keep.append(keeps[0] if isinstance(self.controlnet, FluxControlNetModel) else keeps)
489
+
490
+ # 7. Denoising loop
491
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
492
+ for i, t in enumerate(timesteps):
493
+ if self.interrupt:
494
+ continue
495
+
496
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
497
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
498
+
499
+ if isinstance(self.controlnet, FluxMultiControlNetModel):
500
+ use_guidance = self.controlnet.nets[0].config.guidance_embeds
501
+ else:
502
+ use_guidance = self.controlnet.config.guidance_embeds
503
+
504
+ guidance = torch.tensor([controlnet_guidance_scale], device=device) if use_guidance else None
505
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
506
+
507
+ if isinstance(controlnet_keep[i], list):
508
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
509
+ else:
510
+ controlnet_cond_scale = controlnet_conditioning_scale
511
+ if isinstance(controlnet_cond_scale, list):
512
+ controlnet_cond_scale = controlnet_cond_scale[0]
513
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
514
+
515
+ # controlnet
516
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
517
+ hidden_states=latents,
518
+ controlnet_cond=control_image,
519
+ controlnet_mode=control_mode,
520
+ conditioning_scale=cond_scale,
521
+ timestep=timestep / 1000,
522
+ guidance=guidance,
523
+ pooled_projections=pooled_prompt_embeds,
524
+ encoder_hidden_states=controlnet_prompt_embeds,
525
+ txt_ids=controlnet_text_ids,
526
+ img_ids=latent_image_ids,
527
+ joint_attention_kwargs=self.joint_attention_kwargs,
528
+ return_dict=False,
529
+ )
530
+
531
+ guidance = (
532
+ torch.tensor([guidance_scale], device=device) if self.transformer.config.guidance_embeds else None
533
+ )
534
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
535
+
536
+ noise_pred = self.transformer(
537
+ hidden_states=latents,
538
+ timestep=timestep / 1000,
539
+ guidance=guidance,
540
+ pooled_projections=pooled_prompt_embeds,
541
+ encoder_hidden_states=prompt_embeds,
542
+ controlnet_block_samples=controlnet_block_samples,
543
+ controlnet_single_block_samples=controlnet_single_block_samples,
544
+ txt_ids=text_ids,
545
+ img_ids=latent_image_ids,
546
+ joint_attention_kwargs=self.joint_attention_kwargs,
547
+ return_dict=False,
548
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
549
+ )[0]
550
+
551
+ # perform true CFG
552
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None and negative_text_ids is not None:
553
+ noise_pred_uncond = self.transformer(
554
+ hidden_states=latents,
555
+ timestep=timestep / 1000,
556
+ guidance=guidance,
557
+ pooled_projections=negative_pooled_prompt_embeds,
558
+ encoder_hidden_states=negative_prompt_embeds,
559
+ controlnet_block_samples=None,
560
+ controlnet_single_block_samples=None,
561
+ txt_ids=negative_text_ids,
562
+ img_ids=latent_image_ids,
563
+ joint_attention_kwargs=self.joint_attention_kwargs,
564
+ return_dict=False,
565
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
566
+ )[0]
567
+
568
+ noise_pred = noise_pred_uncond + true_guidance_scale * (noise_pred - noise_pred_uncond)
569
+
570
+ # compute the previous noisy sample x_t -> x_t-1
571
+ latents_dtype = latents.dtype
572
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
573
+
574
+ if latents.dtype != latents_dtype:
575
+ if torch.backends.mps.is_available():
576
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
577
+ latents = latents.to(latents_dtype)
578
+
579
+ if callback_on_step_end is not None:
580
+ callback_kwargs = {}
581
+ for k in callback_on_step_end_tensor_inputs:
582
+ callback_kwargs[k] = locals()[k]
583
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
584
+
585
+ latents = callback_outputs.pop("latents", latents)
586
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
587
+
588
+ # call the callback, if provided
589
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
590
+ progress_bar.update()
591
+
592
+ if XLA_AVAILABLE:
593
+ xm.mark_step()
594
+
595
+ if output_type == "latent":
596
+ image = latents
597
+
598
+ else:
599
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
600
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
601
+
602
+ image = self.vae.decode(latents, return_dict=False)[0]
603
+ image = self.image_processor.postprocess(image, output_type=output_type)
604
+
605
+ # Offload all models
606
+ self.maybe_free_model_hooks()
607
+
608
+ if not return_dict:
609
+ return (image,)
610
+
611
+ return FluxPipelineOutput(images=image)
pipelines/pipeline_infu_flux.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
16
+ import os
17
+ import random
18
+ from typing import Optional
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import torch
23
+ from diffusers.models import FluxControlNetModel
24
+ from facexlib.recognition import init_recognition_model
25
+ from huggingface_hub import snapshot_download
26
+ from insightface.app import FaceAnalysis
27
+ from insightface.utils import face_align
28
+ from PIL import Image
29
+
30
+ from .pipeline_flux_infusenet import FluxInfuseNetPipeline
31
+ from .resampler import Resampler
32
+
33
+
34
+ def seed_everything(seed, deterministic=False):
35
+ """Set random seed.
36
+
37
+ Args:
38
+ seed (int): Seed to be used.
39
+ deterministic (bool): Whether to set the deterministic option for
40
+ CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
41
+ to True and `torch.backends.cudnn.benchmark` to False.
42
+ Default: False.
43
+ """
44
+ random.seed(seed)
45
+ np.random.seed(seed)
46
+ torch.manual_seed(seed)
47
+ torch.cuda.manual_seed(seed)
48
+ torch.cuda.manual_seed_all(seed)
49
+ os.environ['PYTHONHASHSEED'] = str(seed)
50
+ if deterministic:
51
+ torch.backends.cudnn.deterministic = True
52
+ torch.backends.cudnn.benchmark = False
53
+
54
+
55
+ # modified from https://github.com/instantX-research/InstantID/blob/main/pipeline_stable_diffusion_xl_instantid.py
56
+ def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):
57
+ stickwidth = 4
58
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
59
+ kps = np.array(kps)
60
+
61
+ w, h = image_pil.size
62
+ out_img = np.zeros([h, w, 3])
63
+
64
+ for i in range(len(limbSeq)):
65
+ index = limbSeq[i]
66
+ color = color_list[index[0]]
67
+
68
+ x = kps[index][:, 0]
69
+ y = kps[index][:, 1]
70
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
71
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
72
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
73
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
74
+ out_img = (out_img * 0.6).astype(np.uint8)
75
+
76
+ for idx_kp, kp in enumerate(kps):
77
+ color = color_list[idx_kp]
78
+ x, y = kp
79
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
80
+
81
+ out_img_pil = Image.fromarray(out_img.astype(np.uint8))
82
+ return out_img_pil
83
+
84
+
85
+ def extract_arcface_bgr_embedding(in_image, landmark, arcface_model=None, in_settings=None):
86
+ kps = landmark
87
+ arc_face_image = face_align.norm_crop(in_image, landmark=np.array(kps), image_size=112)
88
+ arc_face_image = torch.from_numpy(arc_face_image).unsqueeze(0).permute(0,3,1,2) / 255.
89
+ arc_face_image = 2 * arc_face_image - 1
90
+ arc_face_image = arc_face_image.cuda().contiguous()
91
+ if arcface_model is None:
92
+ arcface_model = init_recognition_model('arcface', device='cuda')
93
+ face_emb = arcface_model(arc_face_image)[0] # [512], normalized
94
+ return face_emb
95
+
96
+
97
+ def resize_and_pad_image(source_img, target_img_size):
98
+ # Get original and target sizes
99
+ source_img_size = source_img.size
100
+ target_width, target_height = target_img_size
101
+
102
+ # Determine the new size based on the shorter side of target_img
103
+ if target_width <= target_height:
104
+ new_width = target_width
105
+ new_height = int(target_width * (source_img_size[1] / source_img_size[0]))
106
+ else:
107
+ new_height = target_height
108
+ new_width = int(target_height * (source_img_size[0] / source_img_size[1]))
109
+
110
+ # Resize the source image using LANCZOS interpolation for high quality
111
+ resized_source_img = source_img.resize((new_width, new_height), Image.LANCZOS)
112
+
113
+ # Compute padding to center resized image
114
+ pad_left = (target_width - new_width) // 2
115
+ pad_top = (target_height - new_height) // 2
116
+
117
+ # Create a new image with white background
118
+ padded_img = Image.new("RGB", target_img_size, (255, 255, 255))
119
+ padded_img.paste(resized_source_img, (pad_left, pad_top))
120
+
121
+ return padded_img
122
+
123
+
124
+ class InfUFluxPipeline:
125
+ def __init__(
126
+ self,
127
+ base_model_path,
128
+ infu_model_path,
129
+ insightface_root_path = './',
130
+ image_proj_num_tokens=8,
131
+ infu_flux_version='v1.0',
132
+ model_version='aes_stage2',
133
+ ):
134
+
135
+ self.infu_flux_version = infu_flux_version
136
+ self.model_version = model_version
137
+
138
+ # Load pipeline
139
+ try:
140
+ infusenet_path = os.path.join(infu_model_path, 'InfuseNetModel')
141
+ self.infusenet = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
142
+ except:
143
+ print("No InfiniteYou model found. Downloading from HuggingFace `ByteDance/InfiniteYou` to `./models/InfiniteYou` ...")
144
+ snapshot_download(repo_id='ByteDance/InfiniteYou', local_dir='./models/InfiniteYou', local_dir_use_symlinks=False)
145
+ infu_model_path = os.path.join('./models/InfiniteYou', f'infu_flux_{infu_flux_version}', model_version)
146
+ infusenet_path = os.path.join(infu_model_path, 'InfuseNetModel')
147
+ self.infusenet = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
148
+ insightface_root_path = './models/InfiniteYou/supports/insightface'
149
+ try:
150
+ pipe = FluxInfuseNetPipeline.from_pretrained(
151
+ base_model_path,
152
+ controlnet=self.infusenet,
153
+ torch_dtype=torch.bfloat16,
154
+ )
155
+ except:
156
+ try:
157
+ pipe = FluxInfuseNetPipeline.from_single_file(
158
+ base_model_path,
159
+ controlnet=self.infusenet,
160
+ torch_dtype=torch.bfloat16,
161
+ )
162
+ except Exception as e:
163
+ print(e)
164
+ print('\nIf you are using `black-forest-labs/FLUX.1-dev` and have not downloaded it into a local directory, '
165
+ 'please accept the agreement and obtain access at https://huggingface.co/black-forest-labs/FLUX.1-dev. '
166
+ 'Then, use `huggingface-cli login` and your access tokens at https://huggingface.co/settings/tokens to authenticate. '
167
+ 'After that, run the code again. If you have downloaded it, please use `base_model_path` to specify the correct path.')
168
+ print('\nIf you are using other models, please download them to a local directory and use `base_model_path` to specify the correct path.')
169
+ exit()
170
+ pipe.to('cuda', torch.bfloat16)
171
+ self.pipe = pipe
172
+
173
+ # Load image proj model
174
+ num_tokens = image_proj_num_tokens
175
+ image_emb_dim = 512
176
+ image_proj_model = Resampler(
177
+ dim=1280,
178
+ depth=4,
179
+ dim_head=64,
180
+ heads=20,
181
+ num_queries=num_tokens,
182
+ embedding_dim=image_emb_dim,
183
+ output_dim=4096,
184
+ ff_mult=4,
185
+ )
186
+ image_proj_model_path = os.path.join(infu_model_path, 'image_proj_model.bin')
187
+ ipm_state_dict = torch.load(image_proj_model_path, map_location="cpu")
188
+ image_proj_model.load_state_dict(ipm_state_dict['image_proj'])
189
+ del ipm_state_dict
190
+ image_proj_model.to('cuda', torch.bfloat16)
191
+ image_proj_model.eval()
192
+
193
+ self.image_proj_model = image_proj_model
194
+
195
+ # Load face encoder
196
+ self.app_640 = FaceAnalysis(name='antelopev2',
197
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
198
+ self.app_640.prepare(ctx_id=0, det_size=(640, 640))
199
+
200
+ self.app_320 = FaceAnalysis(name='antelopev2',
201
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
202
+ self.app_320.prepare(ctx_id=0, det_size=(320, 320))
203
+
204
+ self.app_160 = FaceAnalysis(name='antelopev2',
205
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
206
+ self.app_160.prepare(ctx_id=0, det_size=(160, 160))
207
+
208
+ self.arcface_model = init_recognition_model('arcface', device='cuda')
209
+
210
+ def load_loras(self, loras):
211
+ names, scales = [],[]
212
+ for lora_path, lora_name, lora_scale in loras:
213
+ if lora_path != "":
214
+ print(f"loading lora {lora_path}")
215
+ self.pipe.load_lora_weights(lora_path, adapter_name = lora_name)
216
+ names.append(lora_name)
217
+ scales.append(lora_scale)
218
+
219
+ if len(names) > 0:
220
+ self.pipe.set_adapters(names, adapter_weights=scales)
221
+
222
+ def _detect_face(self, id_image_cv2):
223
+ face_info = self.app_640.get(id_image_cv2)
224
+ if len(face_info) > 0:
225
+ return face_info
226
+
227
+ face_info = self.app_320.get(id_image_cv2)
228
+ if len(face_info) > 0:
229
+ return face_info
230
+
231
+ face_info = self.app_160.get(id_image_cv2)
232
+ return face_info
233
+
234
+ def __call__(
235
+ self,
236
+ id_image: Image.Image, # PIL.Image.Image (RGB)
237
+ prompt: str,
238
+ control_image: Optional[Image.Image] = None, # PIL.Image.Image (RGB) or None
239
+ width = 864,
240
+ height = 1152,
241
+ seed = 42,
242
+ guidance_scale = 3.5,
243
+ num_steps = 30,
244
+ infusenet_conditioning_scale = 1.0,
245
+ infusenet_guidance_start = 0.0,
246
+ infusenet_guidance_end = 1.0,
247
+ ):
248
+ # Extract ID embeddings
249
+ print('Preparing ID embeddings')
250
+ id_image_cv2 = cv2.cvtColor(np.array(id_image), cv2.COLOR_RGB2BGR)
251
+ face_info = self._detect_face(id_image_cv2)
252
+ if len(face_info) == 0:
253
+ raise ValueError('No face detected in the input ID image')
254
+
255
+ face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
256
+ landmark = face_info['kps']
257
+ id_embed = extract_arcface_bgr_embedding(id_image_cv2, landmark, self.arcface_model)
258
+ id_embed = id_embed.clone().unsqueeze(0).float().cuda()
259
+ id_embed = id_embed.reshape([1, -1, 512])
260
+ id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
261
+ with torch.no_grad():
262
+ id_embed = self.image_proj_model(id_embed)
263
+ bs_embed, seq_len, _ = id_embed.shape
264
+ id_embed = id_embed.repeat(1, 1, 1)
265
+ id_embed = id_embed.view(bs_embed * 1, seq_len, -1)
266
+ id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
267
+
268
+ # Load control image
269
+ print('Preparing the control image')
270
+ if control_image is not None:
271
+ control_image = control_image.convert("RGB")
272
+ control_image = resize_and_pad_image(control_image, (width, height))
273
+ face_info = self._detect_face(cv2.cvtColor(np.array(control_image), cv2.COLOR_RGB2BGR))
274
+ if len(face_info) == 0:
275
+ raise ValueError('No face detected in the control image')
276
+ face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
277
+ control_image = draw_kps(control_image, face_info['kps'])
278
+ else:
279
+ out_img = np.zeros([height, width, 3])
280
+ control_image = Image.fromarray(out_img.astype(np.uint8))
281
+
282
+ # Perform inference
283
+ print('Generating image')
284
+ seed_everything(seed)
285
+ image = self.pipe(
286
+ prompt=prompt,
287
+ controlnet_prompt_embeds=id_embed,
288
+ control_image=control_image,
289
+ guidance_scale=guidance_scale,
290
+ num_inference_steps=num_steps,
291
+ controlnet_guidance_scale=1.0,
292
+ controlnet_conditioning_scale=infusenet_conditioning_scale,
293
+ control_guidance_start=infusenet_guidance_start,
294
+ control_guidance_end=infusenet_guidance_end,
295
+ height=height,
296
+ width=width,
297
+ ).images[0]
298
+
299
+ return image
pipelines/resampler.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+
9
+ # FFN
10
+ def FeedForward(dim, mult=4):
11
+ inner_dim = int(dim * mult)
12
+ return nn.Sequential(
13
+ nn.LayerNorm(dim),
14
+ nn.Linear(dim, inner_dim, bias=False),
15
+ nn.GELU(),
16
+ nn.Linear(inner_dim, dim, bias=False),
17
+ )
18
+
19
+
20
+ def reshape_tensor(x, heads):
21
+ bs, length, width = x.shape
22
+ #(bs, length, width) --> (bs, length, n_heads, dim_per_head)
23
+ x = x.view(bs, length, heads, -1)
24
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
25
+ x = x.transpose(1, 2)
26
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
27
+ x = x.reshape(bs, heads, length, -1)
28
+ return x
29
+
30
+
31
+ class PerceiverAttention(nn.Module):
32
+ def __init__(self, *, dim, dim_head=64, heads=8):
33
+ super().__init__()
34
+ self.scale = dim_head**-0.5
35
+ self.dim_head = dim_head
36
+ self.heads = heads
37
+ inner_dim = dim_head * heads
38
+
39
+ self.norm1 = nn.LayerNorm(dim)
40
+ self.norm2 = nn.LayerNorm(dim)
41
+
42
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
43
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
44
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
45
+
46
+ def forward(self, x, latents):
47
+ """
48
+ Args:
49
+ x (torch.Tensor): image features
50
+ shape (b, n1, D)
51
+ latent (torch.Tensor): latent features
52
+ shape (b, n2, D)
53
+ """
54
+ x = self.norm1(x)
55
+ latents = self.norm2(latents)
56
+
57
+ b, l, _ = latents.shape
58
+
59
+ q = self.to_q(latents)
60
+ kv_input = torch.cat((x, latents), dim=-2)
61
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
62
+
63
+ q = reshape_tensor(q, self.heads)
64
+ k = reshape_tensor(k, self.heads)
65
+ v = reshape_tensor(v, self.heads)
66
+
67
+ # attention
68
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
69
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
70
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
71
+ out = weight @ v
72
+
73
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
74
+
75
+ return self.to_out(out)
76
+
77
+
78
+ class Resampler(nn.Module):
79
+ def __init__(
80
+ self,
81
+ dim=1024,
82
+ depth=8,
83
+ dim_head=64,
84
+ heads=16,
85
+ num_queries=8,
86
+ embedding_dim=768,
87
+ output_dim=1024,
88
+ ff_mult=4,
89
+ ):
90
+ super().__init__()
91
+
92
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
93
+
94
+ self.proj_in = nn.Linear(embedding_dim, dim)
95
+
96
+ self.proj_out = nn.Linear(dim, output_dim)
97
+ self.norm_out = nn.LayerNorm(output_dim)
98
+
99
+ self.layers = nn.ModuleList([])
100
+ for _ in range(depth):
101
+ self.layers.append(
102
+ nn.ModuleList(
103
+ [
104
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
105
+ FeedForward(dim=dim, mult=ff_mult),
106
+ ]
107
+ )
108
+ )
109
+
110
+ def forward(self, x):
111
+
112
+ latents = self.latents.repeat(x.size(0), 1, 1)
113
+
114
+ x = self.proj_in(x)
115
+
116
+ for attn, ff in self.layers:
117
+ latents = attn(x, latents) + latents
118
+ latents = ff(latents) + latents
119
+
120
+ latents = self.proj_out(latents)
121
+ return self.norm_out(latents)
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==1.0.1
2
+ diffusers==0.31.0
3
+ facexlib==0.3.0
4
+ gradio==5.21.0
5
+ httpcore==1.0.7
6
+ httpx==0.28.1
7
+ huggingface-hub==0.28.1
8
+ insightface==0.7.3
9
+ numpy==1.26.4
10
+ onnxruntime==1.19.2
11
+ opencv-python==4.11.0.86
12
+ pillow==10.4.0
13
+ pillow-avif-plugin==1.5.0
14
+ pillow-heif==0.21.0
15
+ sentencepiece==0.2.0
16
+ torch==2.2.1
17
+ torchvision==0.17.1
18
+ transformers==4.48.0
19
+ peft==0.14.0