├── .editorconfig
├── .github
├── ISSUE_TEMPLATE.md
└── workflows
│ ├── build-pipeline.yml
│ ├── publish_action.yml
│ ├── publish_node.yml
│ └── validate.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .vscode
└── settings.json
├── Example.JPG
├── LICENSE
├── MANIFEST.in
├── Nodes.JPG
├── README.md
├── __init__.py
├── examples
├── Example_1
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_2
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_3
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_4
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_5
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_6
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_7
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_8
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── Example_9
│ ├── InPainted_Drag_Me_to_ComfyUI.png
│ ├── Masked_Load_Me_in_Loader.png
│ └── Original_No_Mask.png
├── InpaintChara_04.jpg
├── InpaintChara_05.jpg
├── InpaintChara_06.jpg
├── InpaintChara_07.jpg
├── InpaintChara_08.jpg
├── InpaintChara_09.jpg
├── InpaintChara_10.jpg
├── InpaintChara_11.jpg
├── InpaintChara_12.jpg
└── InpaintChara_13.jpg
├── pyproject.toml
├── src
└── LanPaint
│ ├── __init__.py
│ ├── lanpaint.py
│ ├── nodes.py
│ └── utils.py
├── tests
├── __init__.py
├── conftest.py
├── pytest.ini
└── test_LanPaint.py
└── web
└── js
└── example.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | indent_style = space
7 | indent_size = 4
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 | charset = utf-8
11 | end_of_line = lf
12 |
13 | [*.bat]
14 | indent_style = tab
15 | end_of_line = crlf
16 |
17 | [LICENSE]
18 | insert_final_newline = false
19 |
20 | [Makefile]
21 | indent_style = tab
22 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | * LanPaint version:
2 | * Python version:
3 | * Operating System:
4 |
5 | ### Description
6 |
7 | Describe what you were trying to get done.
8 | Tell us what happened, what went wrong, and what you expected to happen.
9 |
10 | ### What I Did
11 |
12 | ```
13 | Paste the command(s) you ran and the output.
14 | If there was a crash, please include the traceback here.
15 | ```
16 |
--------------------------------------------------------------------------------
/.github/workflows/build-pipeline.yml:
--------------------------------------------------------------------------------
1 | # GitHub CI build pipeline
2 | name: LanPaint CI build
3 |
4 | on:
5 | pull_request:
6 | branches:
7 | - master
8 | - main
9 | jobs:
10 | build:
11 | runs-on: ${{ matrix.os }}
12 | env:
13 | PYTHONIOENCODING: "utf8"
14 | strategy:
15 | matrix:
16 | os: [ubuntu-latest]
17 | python-version: ["3.12"]
18 |
19 | steps:
20 | - uses: actions/checkout@v4
21 | - name: Set up Python
22 | uses: actions/setup-python@v5
23 | with:
24 | python-version: ${{ matrix.python-version }}
25 | - name: Install dependencies
26 | run: |
27 | python -m pip install --upgrade pip
28 | pip install .[dev]
29 | - name: Run Linting
30 | run: |
31 | ruff check .
32 | - name: Run Tests
33 | run: |
34 | pytest tests/
35 |
--------------------------------------------------------------------------------
/.github/workflows/publish_action.yml:
--------------------------------------------------------------------------------
1 | name: Publish to Comfy registry
2 | on:
3 | workflow_dispatch:
4 | push:
5 | branches:
6 | - main
7 | paths:
8 | - "pyproject.toml"
9 |
10 | permissions:
11 | issues: write
12 |
13 | jobs:
14 | publish-node:
15 | name: Publish Custom Node to registry
16 | runs-on: ubuntu-latest
17 | if: ${{ github.repository_owner == 'scraed' }}
18 | steps:
19 | - name: Check out code
20 | uses: actions/checkout@v4
21 | - name: Publish Custom Node
22 | uses: Comfy-Org/publish-node-action@v1
23 | with:
24 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} ## Add your own personal access token to your Github Repository secrets and reference it here.
--------------------------------------------------------------------------------
/.github/workflows/publish_node.yml:
--------------------------------------------------------------------------------
1 | name: 📦 Publish to Comfy registry
2 | on:
3 | workflow_dispatch:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | permissions:
9 | issues: write
10 |
11 | jobs:
12 | publish-node:
13 | name: Publish Custom Node to registry
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: ♻️ Check out code
17 | uses: actions/checkout@v4
18 | - name: 📦 Publish Custom Node
19 | uses: Comfy-Org/publish-node-action@main
20 | with:
21 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
22 |
--------------------------------------------------------------------------------
/.github/workflows/validate.yml:
--------------------------------------------------------------------------------
1 | name: Validate backwards compatibility
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - master
7 | - main
8 |
9 | jobs:
10 | validate:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: comfy-org/node-diff@main
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # OSX useful to ignore
7 | *.DS_Store
8 | .AppleDouble
9 | .LSOverride
10 |
11 | # Thumbnails
12 | ._*
13 |
14 | # Files that might appear in the root of a volume
15 | .DocumentRevisions-V100
16 | .fseventsd
17 | .Spotlight-V100
18 | .TemporaryItems
19 | .Trashes
20 | .VolumeIcon.icns
21 | .com.apple.timemachine.donotpresent
22 |
23 | # Directories potentially created on remote AFP share
24 | .AppleDB
25 | .AppleDesktop
26 | Network Trash Folder
27 | Temporary Items
28 | .apdisk
29 |
30 | # C extensions
31 | *.so
32 |
33 | # Distribution / packaging
34 | .Python
35 | env/
36 | venv/
37 | build/
38 | develop-eggs/
39 | dist/
40 | downloads/
41 | eggs/
42 | .eggs/
43 | lib/
44 | lib64/
45 | parts/
46 | sdist/
47 | var/
48 | *.egg-info/
49 | .installed.cfg
50 | *.egg
51 |
52 | # PyInstaller
53 | # Usually these files are written by a python script from a template
54 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
55 | *.manifest
56 | *.spec
57 |
58 | # Installer logs
59 | pip-log.txt
60 | pip-delete-this-directory.txt
61 |
62 | # Unit test / coverage reports
63 | htmlcov/
64 | .tox/
65 | .coverage
66 | .coverage.*
67 | .cache
68 | nosetests.xml
69 | coverage.xml
70 | *,cover
71 | .hypothesis/
72 | .pytest_cache/
73 |
74 | # Translations
75 | *.mo
76 | *.pot
77 |
78 | # Django stuff:
79 | *.log
80 |
81 | # Sphinx documentation
82 | docs/_build/
83 |
84 | # IntelliJ Idea
85 | .idea
86 | *.iml
87 | *.ipr
88 | *.iws
89 |
90 | # PyBuilder
91 | target/
92 |
93 | # Cookiecutter
94 | output/
95 | python_boilerplate/
96 | cookiecutter-pypackage-env/
97 |
98 | # vscode settings
99 | .history/
100 | *.code-workspace
101 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/astral-sh/ruff-pre-commit
3 | # Ruff version.
4 | rev: v0.4.9
5 | hooks:
6 | # Run the linter.
7 | - id: ruff
8 | args: [ --fix ]
9 | # Run the formatter.
10 | - id: ruff-format
11 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | // Required - change /PATH/TO to the absolute path to ComfyUI. Windows e.g.: D:/My Folder/ComfyUI/
3 | // This pulls in ComfyUI Python types for the extension.
4 | "python.analysis.extraPaths": [
5 | "/PATH/TO/ComfyUI/",
6 | "/PATH/TO/ComfyUI/custom_nodes/"
7 | ],
8 | }
9 |
--------------------------------------------------------------------------------
/Example.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/Example.JPG
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 | include README.md
3 |
4 | recursive-exclude * __pycache__
5 | recursive-exclude * *.py[co]
6 |
7 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif
8 |
9 | graft src/LanPaint/web
10 |
--------------------------------------------------------------------------------
/Nodes.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/Nodes.JPG
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LanPaint (Thinking mode Inpaint)
2 |
3 | Unlock precise inpainting without additional training. LanPaint lets the model "think" through multiple iterations before denoising, enabling you to invest more computation time for superior quality.
4 | 
5 |
6 | This is the official implementation of ["Lanpaint: Training-Free Diffusion Inpainting with Exact and Fast Conditional Inference"](https://arxiv.org/abs/2502.03491).
7 |
8 | ## Features
9 |
10 | - **Universal Compatibility** – Works instantly with almost any model (SD 1.5, XL, 3.5, Flux, HiDream, or custom LoRAs) and ControlNet.
11 | - **No Training Needed** – Works out of the box with your existing model.
12 | - **Easy to Use** – Same workflow as standard ComfyUI KSampler.
13 | - **Flexible Masking** – Supports any mask shape, size, or position for inpainting/outpainting.
14 | - **No Workarounds** – Generates 100% new content (no blending or smoothing) without relying on partial denoising.
15 | - **Beyond Inpainting** – You can even use it as a simple way to generate consistent characters.
16 |
17 | ## How It Works
18 | LanPaint uses Langevin Dynamics as "thinking" steps, which digs deeper into the diffusion process and allows the model to generate more consistent results.
19 |
20 | LanPaint introduces "BIG score" that creates a **two-way alignment** between masked and unmasked areas. It continuously evaluates:
21 | - *"Does the new content make sense with the existing elements?"*
22 | - *"Do the existing elements support the new creation?"*
23 | Based on this evaluation, LanPaint iteratively updates the noise in both the masked and unmasked regions.
24 |
25 | LanPaint also implements an accurate, robust, and fast Langevin dynamics solver.
26 |
27 |
28 | ## Quickstart
29 |
30 | 1. **Install ComfyUI**: Follow the official [ComfyUI installation guide](https://docs.comfy.org/get_started) to set up ComfyUI on your system. Or ensure your ComfyUI version > 0.3.11.
31 | 2. **Install ComfyUI-Manager**: Add the [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager) for easy extension management.
32 | 3. **Install LanPaint Nodes**:
33 | - **Via ComfyUI-Manager**: Search for "[LanPaint](https://registry.comfy.org/publishers/scraed/nodes/LanPaint)" in the manager and install it directly.
34 | - **Manually**: Click "Install via Git URL" in ComfyUI-Manager and input the GitHub repository link:
35 | ```
36 | https://github.com/scraed/LanPaint.git
37 | ```
38 | Alternatively, clone this repository into the `ComfyUI/custom_nodes` folder.
39 | 4. **Restart ComfyUI**: Restart ComfyUI to load the LanPaint nodes.
40 |
41 | Once installed, you'll find the LanPaint nodes under the "sampling" category in ComfyUI. Use them just like the default KSampler for high-quality inpainting!
42 |
43 |
44 |
45 | ## Updates
46 | - 2025/06/04
47 | - Add more sampler support.
48 | - Add early stopping to advanced sampler.
49 | - 2025/05/28
50 | - Major update on the Langevin solver. It is now much faster and more stable.
51 | - Greatly simplified the parameters for advanced sampler.
52 | - Fix performance issue on Flux and SD 3.5
53 | - 2025/04/16
54 | - Added Primary HiDream support
55 | - 2025/03/22
56 | - Added Primary Flux support
57 | - Added Tease Mode
58 | - 2025/03/10
59 | - LanPaint has received a major update! All examples now use the LanPaint K Sampler, offering a simplified interface with enhanced performance and stability.
60 |
61 | ## Examples
62 | All examples use a random seed 0 to generate batch of 4 images for fair comparison. (Warning: Generating 4 images may exceed your GPU memory; adjust batch size as needed.)
63 |
64 | ### Example HiDream: InPaint(LanPaint K Sampler, 5 steps of thinking)
65 | 
66 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_8)
67 |
68 | You need to follow the ComfyUI version of [HiDream workflow](https://docs.comfy.org/tutorials/image/hidream/hidream-i1) to download and install the model.
69 |
70 | ### Example SD 3.5: InPaint(LanPaint K Sampler, 5 steps of thinking)
71 | 
72 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_9)
73 |
74 | You need to follow the ComfyUI version of [SD 3.5 workflow](https://comfyui-wiki.com/en/tutorial/advanced/stable-diffusion-3-5-comfyui-workflow) to download and install the model.
75 |
76 | ### Example Flux: InPaint(LanPaint K Sampler, 5 steps of thinking)
77 | 
78 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_7)
79 | [Model Used in This Example](https://huggingface.co/Comfy-Org/flux1-dev/blob/main/flux1-dev-fp8.safetensors)
80 | (Note: Prompt First mode is disabled on Flux. As it does not use CFG guidance.)
81 |
82 | ### Example SDXL 0: Character Consistency (Side View Generation) (LanPaint K Sampler, 5 steps of thinking)
83 | 
84 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_6)
85 | [Model Used in This Example](https://civitai.com/models/1188071?modelVersionId=1408658)
86 |
87 | (Tricks 1: You can emphasize the character by copy it's image multiple times with Photoshop. Here I have made one extra copy.)
88 |
89 | (Tricks 2: Use prompts like multiple views, multiple angles, clone, turnaround. Use LanPaint's Prompt first mode (does not support Flux))
90 |
91 | (Tricks 3: Remeber LanPaint can in-paint: Mask non-consistent regions and try again!)
92 |
93 |
94 | ### Example SDXL 1: Basket to Basket Ball (LanPaint K Sampler, 2 steps of thinking).
95 | 
96 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_1)
97 | [Model Used in This Example](https://civitai.com/models/1188071?modelVersionId=1408658)
98 | ### Example SDXL 2: White Shirt to Blue Shirt (LanPaint K Sampler, 5 steps of thinking)
99 | 
100 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_2)
101 | [Model Used in This Example](https://civitai.com/models/1188071?modelVersionId=1408658)
102 | ### Example SDXL 3: Smile to Sad (LanPaint K Sampler, 5 steps of thinking)
103 | 
104 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_3)
105 | [Model Used in This Example](https://civitai.com/models/133005/juggernaut-xl)
106 | ### Example SDXL 4: Damage Restoration (LanPaint K Sampler, 5 steps of thinking)
107 | 
108 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_4)
109 | [Model Used in This Example](https://civitai.com/models/133005/juggernaut-xl)
110 | ### Example SDXL 5: Huge Damage Restoration (LanPaint K Sampler, 20 steps of thinking)
111 | 
112 | [View Workflow & Masks](https://github.com/scraed/LanPaint/tree/master/examples/Example_5)
113 | [Model Used in This Example](https://civitai.com/models/133005/juggernaut-xl)
114 |
115 | Check more for use cases like inpaint on [fine tuned models](https://github.com/scraed/LanPaint/issues/12#issuecomment-2938662021) and [face swapping](https://github.com/scraed/LanPaint/issues/12#issuecomment-2938723501), thanks to [Amazon90](https://github.com/Amazon90).
116 |
117 |
118 | ## **How to Use These Examples:**
119 | 1. Navigate to the **example** folder (i.e example_1) by clicking **View Workflow & Masks**, download all pictures.
120 | 2. Drag **InPainted_Drag_Me_to_ComfyUI.png** into ComfyUI to load the workflow.
121 | 3. Download the required model from Civitai by clicking **Model Used in This Example**.
122 | 4. Load the model into the **"Load Checkpoint"** node.
123 | 5. Upload **Original_No_Mask.png** to the **"Load image"** node in the **"Original Image"** group (far left).
124 | 6. Upload **Masked_Load_Me_in_Loader.png** to the **"Load image"** node in the **"Mask image for inpainting"** group (second from left).
125 | 7. Queue the task, you will get inpainted results from three methods:
126 | - **[VAE Encode for Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/)** (middle),
127 | - **[Set Latent Noise Mask](https://comfyui-wiki.com/en/tutorial/basic/how-to-inpaint-an-image-in-comfyui)** (second from right),
128 | - **LanPaint** (far right).
129 | 8. You also get an output from "masked blend" node, which copy the original image and paste onto the unmasked part of output. It is useful if you want unmasked region to match original picture pixel perfectly.
130 |
131 | Compare and explore the results from each method!
132 |
133 | 
134 |
135 |
136 | ## Usage
137 |
138 | **Workflow Setup**
139 | Same as default ComfyUI KSampler - simply replace with LanPaint KSampler nodes. The inpainting workflow is the same as the [SetLatentNoiseMask](https://comfyui-wiki.com/zh/comfyui-nodes/latent/inpaint/set-latent-noise-mask) inpainting workflow.
140 |
141 | **Note**
142 | - LanPaint requires binary masks (values of 0 or 1) without opacity or smoothing. To ensure compatibility, set the mask's **opacity and hardness to maximum** in your mask editor. During inpainting, any mask with smoothing or gradients will automatically be converted to a binary mask.
143 | - LanPaint relies heavily on your text prompts to guide inpainting - explicitly describe the content you want generated in the masked area. If results show artifacts or mismatched elements, counteract them with targeted negative prompts.
144 |
145 | ## Basic Sampler
146 | 
147 |
148 | - LanPaint KSampler: The most basic and easy to use sampler for inpainting.
149 | - LanPaint KSampler (Advanced): Full control of all parameters.
150 |
151 | ### LanPaint KSampler
152 | Simplified interface with recommended defaults:
153 |
154 | - Steps: 20 - 50. More steps will give more "thinking" and better results.
155 | - LanPaint NumSteps: The turns of thinking before denoising. Recommend 5 for most of tasks ( which means 5 times slower than sampling without thinking). Use 10 for more challenging tasks.
156 | - LanPaint Prompt mode: Image First mode and Prompt First mode. Image First mode focuses on the image, inpaint based on image context (maybe ignore prompt), while Prompt First mode focuses more on the prompt. Use Prompt First mode for tasks like character consistency. (Technically, it Prompt First mode change CFG scale to negative value in the BIG score to emphasis prompt, which will costs image quality.)
157 |
158 | ### LanPaint KSampler (Advanced)
159 | Full parameter control:
160 | **Key Parameters**
161 |
162 | | Parameter | Range | Description |
163 | |-----------|-------|-------------|
164 | | `Steps` | 0-100 | Total steps of diffusion sampling. Higher means better inpainting. Recommend 20-50. |
165 | | `LanPaint_NumSteps` | 0-20 | Reasoning iterations per denoising step ("thinking depth"). Easy task: 2-5. Hard task: 5-10 |
166 | | `LanPaint_Lambda` | 0.1-50 | Content alignment strength (higher = stricter). Recommend 4.0 - 10.0 |
167 | | `LanPaint_StepSize` | 0.1-1.0 | The StepSize of each thinking step. Recommend 0.1-0.5. |
168 | | `LanPaint_Beta` | 0.1-2.0 | The StepSize ratio between masked / unmasked region. Small value can compensate high lambda values. Recommend 1.0 |
169 | | `LanPaint_Friction` | 0.0-100.0 | The friction of Langevin dynamics. Higher means more slow but stable, lower means fast but unstable. Recommend 10.0 - 20.0|
170 | | `LanPaint_EarlyStop` | 0-10 | Stop LanPaint iteration before the final sampling step. Helps to remove artifacts in some cases. Recommend 1-5|
171 | | `LanPaint_PromptMode` | Image First / Prompt First | Image First mode focuses on the image context, maybe ignore prompt. Prompt First mode focuses more on the prompt. |
172 |
173 | For detailed descriptions of each parameter, simply hover your mouse over the corresponding input field to view tooltips with additional information.
174 |
175 | ### LanPaint Mask Blend
176 | This node blends the original image with the inpainted image based on the mask. It is useful if you want the unmasked region to match the original image pixel perfectly.
177 |
178 | ## LanPaint KSampler (Advanced) Tuning Guide
179 | For challenging inpainting tasks:
180 |
181 | 1️⃣ **Boost Quality**
182 | Increase **total number of sampling steps** (very important!), **LanPaint_NumSteps** (thinking iterations) or **LanPaint_Lambda** if the inpainted result does not meet your expectations.
183 |
184 | 2️⃣ **Boost Speed**
185 | If you want better results but still need fewer steps, consider:
186 | - **Increasing LanPaint_StepSize** to speed up the thinking process.
187 | - **Decreasing LanPaint_Friction** to make the Langevin dynamics converges more faster.
188 |
189 | 3️⃣ **Fix Unstability**:
190 | If you find the results have wired texture, try
191 | - Reduce **LanPaint_Friction** to make the Langevin dynamics more stable.
192 | - Reduce **LanPaint_StepSize** to use smaller step size.
193 | - Reduce **LanPaint_Beta** if you are using a high lambda value.
194 |
195 | ⚠️ **Notes**:
196 | - For effective tuning, **fix the seed** and adjust parameters incrementally while observing the results. This helps isolate the impact of each setting. Better to do it with a batche of images to avoid overfitting on a single image.
197 |
198 | ## ToDo
199 | - Try Implement Detailer
200 | - Provide inference code on without GUI.
201 |
202 | ## Contribute
203 |
204 | - 2025/03/06: Bug Fix for str not callable error and unpack error. Big thanks to [jamesWalker55](https://github.com/jamesWalker55) and [EricBCoding](https://github.com/EricBCoding).
205 |
206 |
207 | ## Citation
208 |
209 | ```
210 | @misc{zheng2025lanpainttrainingfreediffusioninpainting,
211 | title={Lanpaint: Training-Free Diffusion Inpainting with Exact and Fast Conditional Inference},
212 | author={Candi Zheng and Yuan Lan and Yang Wang},
213 | year={2025},
214 | eprint={2502.03491},
215 | archivePrefix={arXiv},
216 | primaryClass={eess.IV},
217 | url={https://arxiv.org/abs/2502.03491},
218 | }
219 | ```
220 |
221 |
222 |
223 |
224 |
225 |
226 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | """Top-level package for LanPaint."""
2 |
3 | __all__ = [
4 | "NODE_CLASS_MAPPINGS",
5 | "NODE_DISPLAY_NAME_MAPPINGS",
6 | "WEB_DIRECTORY",
7 | ]
8 |
9 | __author__ = """LanPaint"""
10 | __email__ = "czhengac@connect.ust.hk"
11 | __version__ = "0.0.1"
12 |
13 | from .src.LanPaint.nodes import NODE_CLASS_MAPPINGS
14 | from .src.LanPaint.nodes import NODE_DISPLAY_NAME_MAPPINGS
15 |
16 | WEB_DIRECTORY = "./web"
17 |
--------------------------------------------------------------------------------
/examples/Example_1/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_1/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_1/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_1/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_1/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_1/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_2/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_2/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_2/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_2/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_2/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_2/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_3/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_3/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_3/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_3/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_3/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_3/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_4/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_4/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_4/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_4/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_4/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_4/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_5/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_5/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_5/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_5/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_5/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_5/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_6/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_6/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_6/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_6/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_6/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_6/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_7/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_7/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_7/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_7/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_7/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_7/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_8/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_8/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_8/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_8/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_8/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_8/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/Example_9/InPainted_Drag_Me_to_ComfyUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_9/InPainted_Drag_Me_to_ComfyUI.png
--------------------------------------------------------------------------------
/examples/Example_9/Masked_Load_Me_in_Loader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_9/Masked_Load_Me_in_Loader.png
--------------------------------------------------------------------------------
/examples/Example_9/Original_No_Mask.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/Example_9/Original_No_Mask.png
--------------------------------------------------------------------------------
/examples/InpaintChara_04.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_04.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_05.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_05.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_06.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_06.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_07.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_07.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_08.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_08.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_09.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_09.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_10.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_10.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_11.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_11.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_12.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_12.jpg
--------------------------------------------------------------------------------
/examples/InpaintChara_13.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/examples/InpaintChara_13.jpg
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=70.0"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "LanPaint"
7 | version = "1.0.3"
8 | description = "Achieve seamless inpainting results without needing a specialized inpainting model."
9 | authors = [
10 | {name = "LanPaint", email = "czhengac@connect.ust.hk"}
11 | ]
12 | readme = "README.md"
13 | license = {text = "GNU General Public License v3"}
14 | classifiers = []
15 | dependencies = [
16 |
17 | ]
18 |
19 | [project.optional-dependencies]
20 | dev = [
21 | "bump-my-version",
22 | "coverage", # testing
23 | "mypy", # linting
24 | "pre-commit", # runs linting on commit
25 | "pytest", # testing
26 | "ruff", # linting
27 | ]
28 |
29 | [project.urls]
30 | bugs = "https://github.com/scraed/LanPaint/issues"
31 | homepage = "https://github.com/scraed/LanPaint"
32 | Repository = "https://github.com/scraed/LanPaint"
33 |
34 | [tool.comfy]
35 | PublisherId = "scraed"
36 | DisplayName = "LanPaint"
37 | Icon = ""
38 |
39 | [tool.setuptools.package-data]
40 | "*" = ["*.*"]
41 |
42 | [tool.pytest.ini_options]
43 | minversion = "8.0"
44 | testpaths = [
45 | "tests",
46 | ]
47 |
48 | [tool.mypy]
49 | files = "."
50 |
51 | # Use strict defaults
52 | strict = true
53 | warn_unreachable = true
54 | warn_no_return = true
55 |
56 | [[tool.mypy.overrides]]
57 | # Don't require test functions to include types
58 | module = "tests.*"
59 | allow_untyped_defs = true
60 | disable_error_code = "attr-defined"
61 |
62 | [tool.ruff]
63 | # extend-exclude = ["static", "ci/templates"]
64 | line-length = 140
65 | src = ["src", "tests"]
66 | target-version = "py39"
67 |
68 | # Add rules to ban exec/eval
69 | [tool.ruff.lint]
70 | select = [
71 | "S102", # exec-builtin
72 | "S307", # eval-used
73 | "W293",
74 | "F", # The "F" series in Ruff stands for "Pyflakes" rules, which catch various Python syntax errors and undefined names.
75 | # See all rules here: https://docs.astral.sh/ruff/rules/#pyflakes-f
76 | ]
77 |
78 | [tool.ruff.lint.flake8-quotes]
79 | inline-quotes = "double"
80 |
--------------------------------------------------------------------------------
/src/LanPaint/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scraed/LanPaint/62870f060ad42db64c28125d6b88aa02271fb2c6/src/LanPaint/__init__.py
--------------------------------------------------------------------------------
/src/LanPaint/lanpaint.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from .utils import *
3 | from functools import partial
4 | class LanPaint():
5 | def __init__(self, Model, NSteps, Friction, Lambda, Beta, StepSize, IS_FLUX = False, IS_FLOW = False):
6 | self.n_steps = NSteps
7 | self.chara_lamb = Lambda
8 | self.IS_FLUX = IS_FLUX
9 | self.IS_FLOW = IS_FLOW
10 | self.step_size = StepSize
11 | self.inner_model = Model
12 | self.friction = Friction
13 | self.chara_beta = Beta
14 |
15 | def __call__(self, x, latent_image, noise, sigma, latent_mask, current_times, model_options, seed, n_steps=None):
16 | self.latent_image = latent_image
17 | self.noise = noise
18 | if n_steps is None:
19 | n_steps = self.n_steps
20 | return self.LanPaint(x, sigma, latent_mask, current_times, n_steps, model_options, seed, self.IS_FLUX, self.IS_FLOW)
21 | def LanPaint(self, x, sigma, latent_mask, current_times, n_steps, model_options, seed, IS_FLUX, IS_FLOW):
22 | VE_Sigma, abt, Flow_t = current_times
23 |
24 |
25 | step_size = self.step_size * (1 - abt)
26 | step_size = step_size[:, None, None, None]
27 | # self.inner_model.inner_model.scale_latent_inpaint returns variance exploding x_t values
28 | # This is the replace step
29 | x = x * (1 - latent_mask) + self.inner_model.inner_model.scale_latent_inpaint(x=x, sigma=sigma, noise=self.noise, latent_image=self.latent_image)* latent_mask
30 |
31 | if IS_FLUX or IS_FLOW:
32 | x_t = x * ( abt[:, None,None,None]**0.5 + (1-abt[:, None,None,None])**0.5 )
33 | else:
34 | x_t = x / ( 1+VE_Sigma[:, None,None,None]**2 )**0.5 # switch to variance perserving x_t values
35 |
36 | ############ LanPaint Iterations Start ###############
37 | # after noise_scaling, noise = latent_image + noise * sigma, which is x_t in the variance exploding diffusion model notation for the known region.
38 | args = None
39 | for i in range(n_steps):
40 | score_func = partial( self.score_model, y = self.latent_image, mask = latent_mask, abt = abt[:, None,None,None], sigma = VE_Sigma[:, None,None,None], tflow = Flow_t[:, None,None,None], model_options = model_options, seed = seed )
41 | x_t, args = self.langevin_dynamics(x_t, score_func , latent_mask, step_size , current_times, sigma_x = self.sigma_x(abt)[:, None,None,None], sigma_y = self.sigma_y(abt)[:, None,None,None], args = args)
42 | if IS_FLUX or IS_FLOW:
43 | x = x_t / ( abt[:, None,None,None]**0.5 + (1-abt[:, None,None,None])**0.5 )
44 | else:
45 | x = x_t * ( 1+VE_Sigma[:, None,None,None]**2 )**0.5 # switch to variance perserving x_t values
46 | ############ LanPaint Iterations End ###############
47 | # out is x_0
48 | out, _ = self.inner_model(x, sigma, model_options=model_options, seed=seed)
49 | out = out * (1-latent_mask) + self.latent_image * latent_mask
50 | return out
51 |
52 | def score_model(self, x_t, y, mask, abt, sigma, tflow, model_options, seed):
53 |
54 | lamb = self.chara_lamb
55 |
56 | if self.IS_FLUX or self.IS_FLOW:
57 | # compute t for flow model, with a small epsilon compensating for numerical error.
58 | x = x_t / ( abt**0.5 + (1-abt)**0.5 ) # switch to Gaussian flow matching
59 | x_0, x_0_BIG = self.inner_model(x, tflow[:, 0,0,0], model_options=model_options, seed=seed)
60 | else:
61 | x = x_t * ( 1+sigma**2 )**0.5 # switch to variance exploding
62 | x_0, x_0_BIG = self.inner_model(x, sigma[:, 0,0,0], model_options=model_options, seed=seed)
63 |
64 | score_x = -(x_t - x_0)
65 | score_y = - (1 + lamb) * ( x_t - y ) + lamb * (x_t - x_0_BIG)
66 | return score_x * (1 - mask) + score_y * mask
67 | def sigma_x(self, abt):
68 | # the time scale for the x_t update
69 | return abt**0
70 | def sigma_y(self, abt):
71 | beta = self.chara_beta * abt ** 0
72 | return beta
73 |
74 | def langevin_dynamics(self, x_t, score, mask, step_size, current_times, sigma_x=1, sigma_y=0, args=None):
75 | # prepare the step size and time parameters
76 | with torch.autocast(device_type=x_t.device.type, dtype=torch.float32):
77 | step_sizes = self.prepare_step_size(current_times, step_size, sigma_x, sigma_y)
78 | sigma, abt, dtx, dty, Gamma_x, Gamma_y, A_x, A_y, D_x, D_y = step_sizes
79 | # print('mask',mask.device)
80 | if torch.mean(dtx) <= 0.:
81 | return x_t, args
82 | # -------------------------------------------------------------------------
83 | # Compute the Langevin dynamics update in variance perserving notation
84 | # -------------------------------------------------------------------------
85 | x0 = self.x0_evalutation(x_t, score, sigma, args)
86 | C = abt**0.5 * x0 / (1-abt)
87 | A = A_x * (1-mask) + A_y * mask
88 | D = D_x * (1-mask) + D_y * mask
89 | dt = dtx * (1-mask) + dty * mask
90 | Gamma = Gamma_x * (1-mask) + Gamma_y * mask
91 |
92 |
93 |
94 | if args is None:
95 | #v = torch.zeros_like(x_t)
96 | v = None
97 | else:
98 | v, = args
99 |
100 | with torch.autocast(device_type=x_t.device.type, dtype=torch.float32):
101 | osc = StochasticHarmonicOscillator(Gamma, A, C, D )
102 | x_t, v = osc.dynamics(x_t, v, dt )
103 |
104 | return x_t, (v,)
105 |
106 | def prepare_step_size(self, current_times, step_size, sigma_x, sigma_y):
107 | # -------------------------------------------------------------------------
108 | # Unpack current times parameters (sigma and abt)
109 | sigma, abt, flow_t = current_times
110 | sigma = sigma[:, None,None,None]
111 | abt = abt[:, None,None,None]
112 | # Compute time step (dtx, dty) for x and y branches.
113 | dtx = 2 * step_size * sigma_x
114 | dty = 2 * step_size * sigma_y
115 |
116 | # -------------------------------------------------------------------------
117 | # Define friction parameter Gamma_hat for each branch.
118 | # Using dtx**0 provides a tensor of the proper device/dtype.
119 |
120 | Gamma_hat_x = self.friction **2 * self.step_size * sigma_x / 0.1 * sigma**0
121 | Gamma_hat_y = self.friction **2 * self.step_size * sigma_y / 0.1 * sigma**0
122 | #print("Gamma_hat_x", torch.mean(Gamma_hat_x).item(), "Gamma_hat_y", torch.mean(Gamma_hat_y).item())
123 | # adjust dt to match denoise-addnoise steps sizes
124 | Gamma_hat_x /= 2.
125 | Gamma_hat_y /= 2.
126 |
127 | A_t_x = (1) / ( 1 - abt ) * dtx / 2
128 | A_t_y = (1) / ( 1 - abt ) * dty / 2
129 |
130 | A_x = A_t_x / (dtx/2)
131 | A_y = A_t_y / (dty/2)
132 | Gamma_x = Gamma_hat_x / (dtx/2)
133 | Gamma_y = Gamma_hat_y / (dty/2)
134 |
135 | #D_x = (2 * (1 + sigma**2) )**0.5
136 | #D_y = (2 * (1 + sigma**2) )**0.5
137 | D_x = (2 * abt**0 )**0.5
138 | D_y = (2 * abt**0 )**0.5
139 | return sigma, abt, dtx/2, dty/2, Gamma_x, Gamma_y, A_x, A_y, D_x, D_y
140 |
141 |
142 |
143 | def x0_evalutation(self, x_t, score, sigma, args):
144 | x0 = x_t + score(x_t)
145 | return x0
--------------------------------------------------------------------------------
/src/LanPaint/nodes.py:
--------------------------------------------------------------------------------
1 | from contextlib import contextmanager
2 | from inspect import cleandoc
3 | import inspect
4 | # import nodes.py
5 | import comfy
6 | import nodes
7 | import latent_preview
8 | from functools import partial
9 | from comfy.utils import repeat_to_batch_size
10 | from comfy.samplers import *
11 | from comfy.model_base import ModelType
12 | from .utils import *
13 | from .lanpaint import LanPaint
14 | # Monkey patch comfy.samplers module by importing with absolute package path
15 | #exec(inspect.getsource(comfy.samplers).replace("from .", "from comfy."))
16 |
17 | def reshape_mask(input_mask, output_shape):
18 | dims = len(output_shape) - 2
19 |
20 |
21 | scale_mode = "nearest-exact"
22 | mask = torch.nn.functional.interpolate(input_mask, size=output_shape[2:], mode=scale_mode)
23 | if mask.shape[1] < output_shape[1]:
24 | mask = mask.repeat((1, output_shape[1]) + (1,) * dims)[:,:output_shape[1]]
25 | mask = repeat_to_batch_size(mask, output_shape[0])
26 | return mask
27 | def prepare_mask(noise_mask, shape, device):
28 | return reshape_mask(noise_mask, shape).to(device)
29 | def sampling_function_LanPaint(model, x, timestep, uncond, cond, cond_scale, cond_scale_BIG, model_options={}, seed=None):
30 | if math.isclose(cond_scale, 1.0) and model_options.get("disable_cfg1_optimization", False) == False:
31 | uncond_ = None
32 | else:
33 | uncond_ = uncond
34 |
35 | conds = [cond, uncond_]
36 | out = calc_cond_batch(model, conds, x, timestep, model_options)
37 |
38 | for fn in model_options.get("sampler_pre_cfg_function", []):
39 | args = {"conds":conds, "conds_out": out, "cond_scale": cond_scale, "timestep": timestep,
40 | "input": x, "sigma": timestep, "model": model, "model_options": model_options}
41 | out = fn(args)
42 |
43 | return cfg_function(model, out[0], out[1], cond_scale, x, timestep, model_options=model_options, cond=cond, uncond=uncond_), cfg_function(model, out[0], out[1], cond_scale_BIG, x, timestep, model_options=model_options, cond=cond, uncond=uncond_)
44 |
45 |
46 | class CFGGuider_LanPaint:
47 | def outer_sample(self, noise, latent_image, sampler, sigmas, denoise_mask=None, callback=None, disable_pbar=False, seed=None):
48 | print("CFGGuider outer_sample")
49 | self.inner_model, self.conds, self.loaded_models = comfy.sampler_helpers.prepare_sampling(self.model_patcher, noise.shape, self.conds, self.model_options)
50 | device = self.model_patcher.load_device
51 |
52 | if denoise_mask is not None:
53 | denoise_mask = prepare_mask(denoise_mask, noise.shape, device)
54 |
55 | noise = noise.to(device)
56 | latent_image = latent_image.to(device)
57 | sigmas = sigmas.to(device)
58 | cast_to_load_options(self.model_options, device=device, dtype=self.model_patcher.model_dtype())
59 |
60 | try:
61 | self.model_patcher.pre_run()
62 | output = self.inner_sample(noise, latent_image, device, sampler, sigmas, denoise_mask, callback, disable_pbar, seed)
63 | finally:
64 | self.model_patcher.cleanup()
65 |
66 | comfy.sampler_helpers.cleanup_models(self.conds, self.loaded_models)
67 | del self.inner_model
68 | del self.loaded_models
69 | return output
70 | def predict_noise(self, x, timestep, model_options={}, seed=None):
71 | return sampling_function_LanPaint(self.inner_model, x, timestep, self.conds.get("negative", None), self.conds.get("positive", None), self.cfg, self.cfg_BIG, model_options=model_options, seed=seed)
72 |
73 | #CFGGuider.outer_sample = CFGGuider_LanPaint.outer_sample
74 | #CFGGuider.predict_noise = CFGGuider_LanPaint.predict_noise
75 |
76 | class KSamplerX0Inpaint:
77 | def __init__(self, model, sigmas):
78 | self.inner_model = model
79 | self.sigmas = sigmas
80 | self.model_sigmas = torch.cat( (torch.tensor([0.], device = sigmas.device) , torch.tensor( self.inner_model.model_patcher.get_model_object("model_sampling").sigmas, device = sigmas.device) ) )
81 | self.model_sigmas = torch.tensor( self.model_sigmas, dtype = self.sigmas.dtype )
82 | def __call__(self, x, sigma, denoise_mask, model_options={}, seed=None,**kwargs):
83 | ### For 1.5 and XL model
84 | # x is x_t in the notation of variance exploding diffusion model, x_t = x_0 + sigma * noise
85 | # sigma is the noise level
86 | ### For flux model
87 | # x is rectified flow x_t = sigma * noise + (1.0 - sigma) * x_0
88 |
89 | IS_FLUX = self.inner_model.inner_model.model_type == ModelType.FLUX
90 | IS_FLOW = self.inner_model.inner_model.model_type == ModelType.FLOW
91 |
92 | # unify the notations into variance exploding diffusion model
93 | if IS_FLUX or IS_FLOW:
94 | Flow_t = sigma
95 | abt = (1 - Flow_t)**2 / ((1 - Flow_t)**2 + Flow_t**2 )
96 | VE_Sigma = Flow_t / (1 - Flow_t)
97 | #print("t", torch.mean( sigma ).item(), "VE_Sigma", torch.mean( VE_Sigma ).item())
98 |
99 |
100 | else:
101 | VE_Sigma = sigma
102 | abt = 1/( 1+VE_Sigma**2 )
103 | Flow_t = (1-abt)**0.5 / ( (1-abt)**0.5 + abt**0.5 )
104 |
105 | if denoise_mask is not None:
106 | if "denoise_mask_function" in model_options:
107 | denoise_mask = model_options["denoise_mask_function"](sigma, denoise_mask, extra_options={"model": self.inner_model, "sigmas": self.sigmas})
108 |
109 | denoise_mask = (denoise_mask > 0.5).float()
110 |
111 | latent_mask = 1 - denoise_mask
112 | current_times = (VE_Sigma, abt, Flow_t)
113 |
114 | current_step = torch.argmin( torch.abs( self.sigmas - torch.mean(sigma) ) )
115 | total_steps = len(self.sigmas)-1
116 |
117 | if total_steps - current_step <= self.LanPaint_early_stop:
118 | out = self.PaintMethod(x, self.latent_image, self.noise, sigma, latent_mask, current_times, model_options, seed, n_steps=0)
119 | else:
120 | out = self.PaintMethod(x, self.latent_image, self.noise, sigma, latent_mask, current_times, model_options, seed)
121 | else:
122 | out, _ = self.inner_model(x, sigma, model_options=model_options, seed=seed)
123 |
124 | # Add TAESD preview support - directly use the latent_preview module
125 | current_step = model_options.get("i", kwargs.get("i", 0))
126 | total_steps = model_options.get("total_steps", 0)
127 |
128 | # Only show preview every few steps to improve performance
129 | if current_step % 2 == 0:
130 | # Directly call the preview callback if it exists
131 | callback = model_options.get("callback", None)
132 | if callback is not None:
133 | callback({"i": current_step, "denoised": out, "x": x})
134 |
135 | return out
136 |
137 | # Custom sampler class extending ComfyUI's KSAMPLER for LanPaint
138 | class KSAMPLER(comfy.samplers.KSAMPLER):
139 | def sample(self, model_wrap, sigmas, extra_args, callback, noise, latent_image=None, denoise_mask=None, disable_pbar=False):
140 | #noise here is a randn noise from comfy.sample.prepare_noise
141 | #latent_image is the latent image as input of the KSampler node. For inpainting, it is the masked latent image. Otherwise it is zero tensor.
142 | extra_args["denoise_mask"] = denoise_mask
143 | model_k = KSamplerX0Inpaint(model_wrap, sigmas)
144 | model_k.latent_image = latent_image
145 | if self.inpaint_options.get("random", False): #TODO: Should this be the default?
146 | generator = torch.manual_seed(extra_args.get("seed", 41) + 1)
147 | model_k.noise = torch.randn(noise.shape, generator=generator, device="cpu").to(noise.dtype).to(noise.device)
148 | else:
149 | model_k.noise = noise
150 |
151 | IS_FLUX = model_wrap.inner_model.model_type == ModelType.FLUX
152 | IS_FLOW = model_wrap.inner_model.model_type == ModelType.FLOW
153 | # unify the notations into variance exploding diffusion model
154 | if IS_FLUX:
155 | model_wrap.cfg_BIG = 1.0
156 | else:
157 | model_wrap.cfg_BIG = model_wrap.model_patcher.LanPaint_cfg_BIG
158 | noise = model_wrap.inner_model.model_sampling.noise_scaling(sigmas[0], noise, latent_image, self.max_denoise(model_wrap, sigmas))
159 |
160 | model_k.PaintMethod = LanPaint(model_k.inner_model,
161 | model_wrap.model_patcher.LanPaint_NumSteps,
162 | model_wrap.model_patcher.LanPaint_Friction,
163 | model_wrap.model_patcher.LanPaint_Lambda,
164 | model_wrap.model_patcher.LanPaint_Beta,
165 | model_wrap.model_patcher.LanPaint_StepSize,
166 | IS_FLUX = IS_FLUX,
167 | IS_FLOW = IS_FLOW)
168 | model_k.LanPaint_early_stop = model_wrap.model_patcher.LanPaint_EarlyStop
169 | #if not inpainting, after noise_scaling, noise = noise * sigma, which is the noise added to the clean latent image in the variance exploding diffusion model notation.
170 | #if inpainting, after noise_scaling, noise = latent_image + noise * sigma, which is x_t in the variance exploding diffusion model notation for the known region.
171 | k_callback = None
172 | total_steps = len(sigmas) - 1
173 | if callback is not None:
174 | k_callback = lambda x: callback(x["i"], x["denoised"], x["x"], total_steps)
175 | #print("LanPaint KSampler call sampler_function", self.sampler_function)
176 | # The main loop!
177 | #print("##########")
178 | #print("Sampling with ", self.sampler_function)
179 | #print("##########")
180 | samples = self.sampler_function(model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar, **self.extra_options)
181 | #print("LanPaint KSampler end sampler_function")
182 | samples = model_wrap.inner_model.model_sampling.inverse_noise_scaling(sigmas[-1], samples)
183 | return samples
184 |
185 | @contextmanager
186 | def override_sample_function():
187 | original_outer_sample = comfy.samplers.CFGGuider.outer_sample
188 | comfy.samplers.CFGGuider.outer_sample = CFGGuider_LanPaint.outer_sample
189 |
190 | original_predict_noise = comfy.samplers.CFGGuider.predict_noise
191 | comfy.samplers.CFGGuider.predict_noise = CFGGuider_LanPaint.predict_noise
192 |
193 | original_sample = comfy.samplers.KSAMPLER.sample
194 | comfy.samplers.KSAMPLER.sample = KSAMPLER.sample
195 |
196 | try:
197 | yield
198 | finally:
199 | comfy.samplers.KSAMPLER.sample = original_sample
200 | comfy.samplers.CFGGuider.predict_noise = original_predict_noise
201 | comfy.samplers.CFGGuider.outer_sample = original_outer_sample
202 |
203 |
204 | class LanPaint_UpSale_LatentNoiseMask:
205 | @classmethod
206 | def INPUT_TYPES(s):
207 | return {"required": { "samples": ("LATENT",),
208 | "scale": ("INT", {"default": 2, "min": 2, "max": 8, "step": 1}),
209 | }}
210 | RETURN_TYPES = ("LATENT",)
211 | FUNCTION = "set_mask"
212 |
213 |
214 | CATEGORY = "latent/inpaint"
215 |
216 | def set_mask(self, samples, scale):
217 | s = samples.copy()
218 | samples = s['samples']
219 | # generate a mask with every scaleth pixel set to 1
220 | mask = torch.zeros(samples.shape[0], 1, samples.shape[2], samples.shape[3], device=samples.device) + 1
221 | mask[:, :, ::scale, ::scale] = 0
222 | s["noise_mask"] = mask
223 | return (s,)
224 |
225 | #KSAMPLER_NAMES = ["euler", "dpmpp_2m", "uni_pc"]
226 | KSAMPLER_NAMES = ["euler","euler_ancestral", "heun", "heunpp2","dpm_2", "dpm_2_ancestral",
227 | "dpm_fast", "dpmpp_sde", "dpmpp_sde_gpu",
228 | "dpmpp_2m", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddpm",
229 | "deis", "res_multistep", "res_multistep_ancestral",
230 | "gradient_estimation", "er_sde", "seeds_2", "seeds_3"]
231 |
232 | class LanPaint_KSampler():
233 | @classmethod
234 | def INPUT_TYPES(s):
235 | return {
236 | "required": {
237 | "model": ("MODEL", {"tooltip": "The model used for denoising the input latent."}),
238 | "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "The random seed used for creating the noise."}),
239 | "steps": ("INT", {"default": 30, "min": 1, "max": 10000, "tooltip": "The number of steps used in the denoising process."}),
240 | "cfg": ("FLOAT", {"default": 5.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01, "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality."}),
241 | "sampler_name": (KSAMPLER_NAMES, {"tooltip": "Recommended: euler."}),
242 | "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"default": "karras", "tooltip": "The scheduler controls how noise is gradually removed to form the image."}),
243 | "positive": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to include in the image."}),
244 | "negative": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to exclude from the image."}),
245 | "latent_image": ("LATENT", {"tooltip": "The latent image to denoise."}),
246 | "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling."}),
247 | "LanPaint_NumSteps": ("INT", {"default": 5, "min": 0, "max": 100, "tooltip": "The number of steps for the Langevin dynamics, representing the turns of thinking per step."}),
248 | "LanPaint_PromptMode": (["Image First", "Prompt First"], {"tooltip": "Image First: emphasis image quality, Prompt First: emphasis prompt following"}),
249 | "LanPaint_Info": ("STRING", {"default": "LanPaint KSampler. For more info, visit https://github.com/scraed/LanPaint. If you find it useful, please give a star ⭐️!", "multiline": True}),
250 | }
251 | }
252 |
253 | RETURN_TYPES = ("LATENT",)
254 | OUTPUT_TOOLTIPS = ("The denoised latent.",)
255 | FUNCTION = "sample"
256 |
257 | CATEGORY = "sampling"
258 | DESCRIPTION = "Uses the provided model, positive and negative conditioning to denoise the latent image."
259 |
260 | def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0, LanPaint_NumSteps=5, LanPaint_PromptMode = "Image First", LanPaint_Info=""):
261 |
262 | model.LanPaint_StepSize = 0.15
263 | model.LanPaint_Lambda = 8.0
264 | model.LanPaint_Beta = 1.0
265 | model.LanPaint_NumSteps = LanPaint_NumSteps
266 | model.LanPaint_Friction = 15.
267 | model.LanPaint_EarlyStop = 1
268 | if LanPaint_PromptMode == "Image First":
269 | model.LanPaint_cfg_BIG = cfg
270 | else:
271 | model.LanPaint_cfg_BIG = 0*cfg - 0.5
272 | with override_sample_function():
273 | return nodes.common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
274 | class LanPaint_KSamplerAdvanced:
275 | @classmethod
276 | def INPUT_TYPES(s):
277 | return {"required":
278 | {"model": ("MODEL",),
279 | "add_noise": (["enable", "disable"], ),
280 | "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
281 | "steps": ("INT", {"default": 30, "min": 1, "max": 10000}),
282 | "cfg": ("FLOAT", {"default": 5.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
283 | "sampler_name": (KSAMPLER_NAMES, ),
284 | "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
285 | "positive": ("CONDITIONING", ),
286 | "negative": ("CONDITIONING", ),
287 | "latent_image": ("LATENT", ),
288 | "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
289 | "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
290 | "return_with_leftover_noise": (["disable", "enable"], ),
291 | "LanPaint_NumSteps": ("INT", {"default": 5, "min": 0, "max": 100, "tooltip": "The number of steps for the Langevin dynamics, representing the turns of thinking per step."}),
292 | "LanPaint_Lambda": ("FLOAT", {"default": 8., "min": 0.1, "max": 50.0, "step": 0.1, "round": 0.1, "tooltip": "The bidirectional guidance scale. Higher values align with known regions more closely, but may result in instability."}),
293 | "LanPaint_StepSize": ("FLOAT", {"default": 0.15, "min": 0.0001, "max": 1., "step": 0.01, "round": 0.001, "tooltip": "The step size for the Langevin dynamics. Higher values result in faster convergence but may be unstable."}),
294 | "LanPaint_Beta": ("FLOAT", {"default": 1., "min": 0.0001, "max": 5, "step": 0.1, "round": 0.1, "tooltip": "The step size ratio between masked / unmasked regions. Lower value can compensate high values of LanPaint_Lambda."}),
295 | "LanPaint_Friction": ("FLOAT", {"default": 15, "min": 0., "max": 50.0, "step": 0.1, "round": 0.1, "tooltip": "The friction parameter for fast langevin, lower values result in faster convergence but may be unstable."}),
296 | "LanPaint_PromptMode": (["Image First", "Prompt First"], {"tooltip": "Image First: emphasis image quality, Prompt First: emphasis prompt following"}),
297 | "LanPaint_EarlyStop": ("INT", {"default": 1, "min": 0, "max": 10000, "tooltip": "The number of steps to stop the LanPaint early, useful for preventing the image from irregular patterns."}),
298 | "LanPaint_Info": ("STRING", {"default": "LanPaint KSampler Adv. For more info, visit https://github.com/scraed/LanPaint. If you find it useful, please give a star ⭐️!", "multiline": True}),
299 | },
300 | }
301 |
302 | RETURN_TYPES = ("LATENT",)
303 | FUNCTION = "sample"
304 |
305 | CATEGORY = "sampling"
306 |
307 | def sample(self, model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, denoise=1.0, LanPaint_StepSize=0.05, LanPaint_Lambda=5, LanPaint_Beta=1, LanPaint_NumSteps=5, LanPaint_Friction=5, LanPaint_PromptMode = "Image First", LanPaint_EarlyStop = 1, LanPaint_Info=""):
308 | force_full_denoise = True
309 | if return_with_leftover_noise == "enable":
310 | force_full_denoise = False
311 | disable_noise = False
312 | if add_noise == "disable":
313 | disable_noise = True
314 | model.LanPaint_StepSize = LanPaint_StepSize
315 | model.LanPaint_Lambda = LanPaint_Lambda
316 | model.LanPaint_Beta = LanPaint_Beta
317 | model.LanPaint_NumSteps = LanPaint_NumSteps
318 | model.LanPaint_Friction = LanPaint_Friction
319 | model.LanPaint_EarlyStop = LanPaint_EarlyStop
320 | if LanPaint_PromptMode == "Image First":
321 | model.LanPaint_cfg_BIG = cfg
322 | else:
323 | model.LanPaint_cfg_BIG = 0*cfg - 0.5
324 |
325 | with override_sample_function():
326 | return nodes.common_ksampler(model, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise)
327 |
328 |
329 | class MaskBlend:
330 | def __init__(self):
331 | pass
332 |
333 | @classmethod
334 | def INPUT_TYPES(s):
335 | return {
336 | "required": {
337 | "image1": ("IMAGE",),
338 | "image2": ("IMAGE",),
339 | "mask": ("MASK",),
340 | "blend_overlap": ("INT", {"default": 1, "min": 1, "max": 51, "step": 2, "tooltip": "The number of pixels to blend between the two images."})
341 | },
342 | }
343 |
344 | RETURN_TYPES = ("IMAGE",)
345 | FUNCTION = "blend_images"
346 |
347 | CATEGORY = "image/postprocessing"
348 |
349 | def blend_images(self, image1: torch.Tensor, image2: torch.Tensor, mask: torch.Tensor, blend_overlap: int):
350 | # smooth the binary 01 mask, keep 1 still 1, but smooth the transition from 1 to 0
351 | # for each mask pixel, find out the nearest 1 pixel, and set the mask value to the distance between the two pixels
352 | mask = mask.float()
353 | mask = torch.nn.functional.max_pool2d(mask, kernel_size=blend_overlap, stride=1, padding=blend_overlap//2)
354 | # apply Gaussian blur with kernel size blend_overlap
355 | kernel = self.gaussian_kernel(blend_overlap)
356 | kernel = kernel.to(image1.device)
357 | kernel = kernel[None, None, ...]
358 |
359 | mask = torch.nn.functional.conv2d(mask[:,None,:,:], kernel, padding=blend_overlap//2)[:,0,:,:]
360 |
361 |
362 | blended_image = image1 * (1 - mask[...,None]) + image2 * mask[...,None]
363 | return (blended_image,)
364 | def gaussian_kernel(self,kernel_size):
365 | """
366 | Creates a 2D Gaussian kernel with the given size and standard deviation (sigma).
367 | """
368 | sigma = (kernel_size - 1)/4
369 | # Create a grid of (x, y) coordinates
370 | x = torch.arange(kernel_size).float() - kernel_size // 2
371 | y = torch.arange(kernel_size).float() - kernel_size // 2
372 | x_grid, y_grid = torch.meshgrid(x, y, indexing='ij')
373 |
374 | # Compute the Gaussian function
375 | kernel = torch.exp(-(x_grid ** 2 + y_grid ** 2) / (2 * sigma ** 2))
376 | kernel = kernel / kernel.sum() # Normalize the kernel
377 |
378 | return kernel
379 |
380 |
381 | # A dictionary that contains all nodes you want to export with their names
382 | # NOTE: names should be globally unique
383 | NODE_CLASS_MAPPINGS = {
384 | "LanPaint_KSampler": LanPaint_KSampler,
385 | "LanPaint_KSamplerAdvanced": LanPaint_KSamplerAdvanced,
386 | "LanPaint_MaskBlend": MaskBlend,
387 | # "LanPaint_UpSale_LatentNoiseMask": LanPaint_UpSale_LatentNoiseMask,
388 | }
389 |
390 | # A dictionary that contains the friendly/humanly readable titles for the nodes
391 | NODE_DISPLAY_NAME_MAPPINGS = {
392 | "LanPaint_KSampler": "LanPaint KSampler",
393 | "LanPaint_KSamplerAdvanced": "LanPaint KSampler (Advanced)",
394 | "LanPaint_MaskBlend": "LanPaint Mask Blend",
395 | # "LanPaint_UpSale_LatentNoiseMask": "LanPaint UpSale Latent Noise Mask"
396 | }
397 |
--------------------------------------------------------------------------------
/src/LanPaint/utils.py:
--------------------------------------------------------------------------------
1 | import torch
2 | def epxm1_x(x):
3 | # Compute the (exp(x) - 1) / x term with a small value to avoid division by zero.
4 | result = torch.special.expm1(x) / x
5 | # replace NaN or inf values with 0
6 | result = torch.where(torch.isfinite(result), result, torch.zeros_like(result))
7 | mask = torch.abs(x) < 1e-2
8 | result = torch.where(mask, 1 + x/2. + x**2 / 6., result)
9 | return result
10 | def epxm1mx_x2(x):
11 | # Compute the (exp(x) - 1 - x) / x**2 term with a small value to avoid division by zero.
12 | result = (torch.special.expm1(x) - x) / x**2
13 | # replace NaN or inf values with 0
14 | result = torch.where(torch.isfinite(result), result, torch.zeros_like(result))
15 | mask = torch.abs(x**2) < 1e-2
16 | result = torch.where(mask, 1/2. + x/6 + x**2 / 24 + x**3 / 120, result)
17 | return result
18 |
19 | def expm1mxmhx2_x3(x):
20 | # Compute the (exp(x) - 1 - x - x**2 / 2) / x**3 term with a small value to avoid division by zero.
21 | result = (torch.special.expm1(x) - x - x**2 / 2) / x**3
22 | # replace NaN or inf values with 0
23 | result = torch.where(torch.isfinite(result), result, torch.zeros_like(result))
24 | mask = torch.abs(x**3) < 1e-2
25 | result = torch.where(mask, 1/6 + x/24 + x**2 / 120 + x**3 / 720 + x**4 / 5040, result)
26 | return result
27 |
28 | def exp_1mcosh_GD(gamma_t, delta):
29 | """
30 | Compute e^(-Γt) * (1 - cosh(Γt√Δ))/ ( (Γt)**2 Δ )
31 |
32 | Parameters:
33 | gamma_t: Γ*t term (could be a scalar or tensor)
34 | delta: Δ term (could be a scalar or tensor)
35 |
36 | Returns:
37 | Result of the computation with numerical stability handling
38 | """
39 | # Main computation
40 | is_positive = delta > 0
41 | sqrt_abs_delta = torch.sqrt(torch.abs(delta))
42 | gamma_t_sqrt_delta = gamma_t * sqrt_abs_delta
43 | numerator_pos = torch.exp(-gamma_t) - (torch.exp(gamma_t * (sqrt_abs_delta - 1)) + torch.exp(gamma_t * (-sqrt_abs_delta - 1))) / 2
44 | numerator_neg = torch.exp(-gamma_t) * ( 1 - torch.cos(gamma_t * sqrt_abs_delta ) )
45 | numerator = torch.where(is_positive, numerator_pos, numerator_neg)
46 | result = numerator / (delta * gamma_t**2 )
47 | # Handle NaN/inf cases
48 | result = torch.where(torch.isfinite(result), result, torch.zeros_like(result))
49 | # Handle numerical instability for small delta
50 | mask = torch.abs(gamma_t_sqrt_delta**2) < 5e-2
51 | taylor = ( -0.5 - gamma_t**2 / 24 * delta - gamma_t**4 / 720 * delta**2 ) * torch.exp(-gamma_t)
52 | result = torch.where(mask, taylor, result)
53 | return result
54 |
55 | def exp_sinh_GsqrtD(gamma_t, delta):
56 | """
57 | Compute e^(-Γt) * sinh(Γt√Δ) / (Γt√Δ)
58 |
59 | Parameters:
60 | gamma_t: Γ*t term (could be a scalar or tensor)
61 | delta: Δ term (could be a scalar or tensor)
62 |
63 | Returns:
64 | Result of the computation with numerical stability handling
65 | """
66 | # Main computation
67 | is_positive = delta > 0
68 | sqrt_abs_delta = torch.sqrt(torch.abs(delta))
69 | gamma_t_sqrt_delta = gamma_t * sqrt_abs_delta
70 | numerator_pos = (torch.exp(gamma_t * (sqrt_abs_delta - 1)) - torch.exp(gamma_t * (-sqrt_abs_delta - 1))) / 2
71 | denominator_pos = gamma_t_sqrt_delta
72 | result_pos = numerator_pos / gamma_t_sqrt_delta
73 | result_pos = torch.where(torch.isfinite(result_pos), result_pos, torch.zeros_like(result_pos))
74 |
75 | # Taylor expansion for small gamma_t_sqrt_delta
76 | mask = torch.abs(gamma_t_sqrt_delta) < 1e-2
77 | taylor = ( 1 + gamma_t**2 / 6 * delta + gamma_t**4 / 120 * delta**2 ) * torch.exp(-gamma_t)
78 | result_pos = torch.where(mask, taylor, result_pos)
79 |
80 | # Handle negative delta
81 | result_neg = torch.exp(-gamma_t) * torch.special.sinc(gamma_t_sqrt_delta/torch.pi)
82 | result = torch.where(is_positive, result_pos, result_neg)
83 | return result
84 |
85 | def exp_cosh(gamma_t, delta):
86 | """
87 | Compute e^(-Γt) * cosh(Γt√Δ)
88 |
89 | Parameters:
90 | gamma_t: Γ*t term (could be a scalar or tensor)
91 | delta: Δ term (could be a scalar or tensor)
92 |
93 | Returns:
94 | Result of the computation with numerical stability handling
95 | """
96 | exp_1mcosh_GD_result = exp_1mcosh_GD(gamma_t, delta) # e^(-Γt) * (1 - cosh(Γt√Δ))/ ( (Γt)**2 Δ )
97 | result = torch.exp(-gamma_t) - gamma_t**2 * delta * exp_1mcosh_GD_result
98 | return result
99 | def exp_sinh_sqrtD(gamma_t, delta):
100 | """
101 | Compute e^(-Γt) * sinh(Γt√Δ) / √Δ
102 | Parameters:
103 | gamma_t: Γ*t term (could be a scalar or tensor)
104 | delta: Δ term (could be a scalar or tensor)
105 | Returns:
106 | Result of the computation with numerical stability handling
107 | """
108 | exp_sinh_GsqrtD_result = exp_sinh_GsqrtD(gamma_t, delta) # e^(-Γt) * sinh(Γt√Δ) / (Γt√Δ)
109 | result = gamma_t * exp_sinh_GsqrtD_result
110 | return result
111 |
112 |
113 |
114 | def zeta1(gamma_t, delta):
115 | # Compute hyperbolic terms and exponential
116 | half_gamma_t = gamma_t / 2
117 | exp_cosh_term = exp_cosh(half_gamma_t, delta)
118 | exp_sinh_term = exp_sinh_sqrtD(half_gamma_t, delta)
119 |
120 |
121 | # Main computation
122 | numerator = 1 - (exp_cosh_term + exp_sinh_term)
123 | denominator = gamma_t * (1 - delta) / 4
124 | result = 1 - numerator / denominator
125 |
126 | # Handle numerical instability
127 | result = torch.where(torch.isfinite(result), result, torch.zeros_like(result))
128 |
129 | # Taylor expansion for small x (similar to your epxm1Dx approach)
130 | mask = torch.abs(denominator) < 5e-3
131 | term1 = epxm1_x(-gamma_t)
132 | term2 = epxm1mx_x2(-gamma_t)
133 | term3 = expm1mxmhx2_x3(-gamma_t)
134 | taylor = term1 + (1/2.+ term1-3*term2)*denominator + (-1/6. + term1/2 - 4 * term2 + 10 * term3) * denominator**2
135 | result = torch.where(mask, taylor, result)
136 |
137 | return result
138 |
139 | def exp_cosh_minus_terms(gamma_t, delta):
140 | """
141 | Compute E^(-tΓ) * (Cosh[tΓ] - 1 - (Cosh[tΓ√Δ] - 1)/Δ) / (tΓ(1 - Δ))
142 |
143 | Parameters:
144 | gamma_t: Γ*t term (could be a scalar or tensor)
145 | delta: Δ term (could be a scalar or tensor)
146 |
147 | Returns:
148 | Result of the computation with numerical stability handling
149 | """
150 | exp_term = torch.exp(-gamma_t)
151 | # Compute individual terms
152 | exp_cosh_term = exp_cosh(gamma_t, gamma_t**0) - exp_term # E^(-tΓ) (Cosh[tΓ] - 1) term
153 | exp_cosh_delta_term = - gamma_t**2 * exp_1mcosh_GD(gamma_t, delta) # E^(-tΓ) (Cosh[tΓ√Δ] - 1)/Δ term
154 |
155 | #exp_1mcosh_GD e^(-Γt) * (1 - cosh(Γt√Δ))/ ( (Γt)**2 Δ )
156 | # Main computation
157 | numerator = exp_cosh_term - exp_cosh_delta_term
158 | denominator = gamma_t * (1 - delta)
159 |
160 | result = numerator / denominator
161 |
162 | # Handle numerical instability
163 | result = torch.where(torch.isfinite(result), result, torch.zeros_like(result))
164 |
165 | # Taylor expansion for small gamma_t and delta near 1
166 | mask = (torch.abs(denominator) < 1e-1)
167 | exp_1mcosh_GD_term = exp_1mcosh_GD(gamma_t, delta**0)
168 | taylor = (
169 | gamma_t*exp_1mcosh_GD_term + 0.5 * gamma_t * exp_sinh_GsqrtD(gamma_t, delta**0)
170 | - denominator / 4 * ( 0.5 * exp_cosh(gamma_t, delta**0) - 4 * exp_1mcosh_GD_term - 5 /2 * exp_sinh_GsqrtD(gamma_t, delta**0) )
171 | )
172 | result = torch.where(mask, taylor, result)
173 |
174 | return result
175 |
176 |
177 | def zeta2(gamma_t, delta):
178 | half_gamma_t = gamma_t / 2
179 | return exp_sinh_GsqrtD(half_gamma_t, delta)
180 |
181 | def sig11(gamma_t, delta):
182 | return 1 - torch.exp(-gamma_t) + gamma_t**2 * exp_1mcosh_GD(gamma_t, delta) + exp_sinh_sqrtD(gamma_t, delta)
183 |
184 |
185 | def Zcoefs(gamma_t, delta):
186 | Zeta1 = zeta1(gamma_t, delta)
187 | Zeta2 = zeta2(gamma_t, delta)
188 |
189 | sq_total = 1 - Zeta1 + gamma_t * (delta - 1) * (Zeta1 - 1)**2 / 8
190 | amplitude = torch.sqrt(sq_total)
191 | Zcoef1 = ( gamma_t**0.5 * Zeta2 / 2 **0.5 ) / amplitude
192 | Zcoef2 = Zcoef1 * gamma_t *( - 2 * exp_1mcosh_GD(gamma_t, delta) / sig11(gamma_t, delta) ) ** 0.5
193 | #cterm = exp_cosh_minus_terms(gamma_t, delta)
194 | #sterm = exp_sinh_sqrtD(gamma_t, delta**0) + exp_sinh_sqrtD(gamma_t, delta)
195 | #Zcoef3 = 2 * torch.sqrt( cterm / ( gamma_t * (1 - delta) * cterm + sterm ) )
196 | Zcoef3 = torch.sqrt( torch.maximum(1 - Zcoef1**2 - Zcoef2**2, sq_total.new_zeros(sq_total.shape)) )
197 |
198 | return Zcoef1 * amplitude, Zcoef2 * amplitude, Zcoef3 * amplitude, amplitude
199 |
200 | def Zcoefs_asymp(gamma_t, delta):
201 | A_t = (gamma_t * (1 - delta) )/4
202 | return epxm1_x(- 2 * A_t)
203 |
204 | class StochasticHarmonicOscillator:
205 | """
206 | Simulates a stochastic harmonic oscillator governed by the equations:
207 | dy(t) = q(t) dt
208 | dq(t) = -Γ A y(t) dt + Γ C dt + Γ D dw(t) - Γ q(t) dt
209 |
210 | Also define v(t) = q(t) / √Γ, which is numerically more stable.
211 |
212 | Where:
213 | y(t) - Position variable
214 | q(t) - Velocity variable
215 | Γ - Damping coefficient
216 | A - Harmonic potential strength
217 | C - Constant force term
218 | D - Noise amplitude
219 | dw(t) - Wiener process (Brownian motion)
220 | """
221 | def __init__(self, Gamma, A, C, D):
222 | self.Gamma = Gamma
223 | self.A = A
224 | self.C = C
225 | self.D = D
226 | self.Delta = 1 - 4 * A / Gamma
227 | def sig11(self, gamma_t, delta):
228 | return 1 - torch.exp(-gamma_t) + gamma_t**2 * exp_1mcosh_GD(gamma_t, delta) + exp_sinh_sqrtD(gamma_t, delta)
229 | def sig22(self, gamma_t, delta):
230 | return 1- zeta1(2*gamma_t, delta) + 2 * gamma_t * exp_1mcosh_GD(gamma_t, delta)
231 | def dynamics(self, y0, v0, t):
232 | """
233 | Calculates the position and velocity variables at time t.
234 |
235 | Parameters:
236 | y0 (float): Initial position
237 | v0 (float): Initial velocity v(0) = q(0) / √Γ
238 | t (float): Time at which to evaluate the dynamics
239 | Returns:
240 | tuple: (y(t), v(t))
241 | """
242 |
243 |
244 | dummyzero = y0.new_zeros(1) # convert scalar to tensor with same device and dtype as y0
245 | Delta = self.Delta + dummyzero
246 | Gamma_hat = self.Gamma * t + dummyzero
247 | A = self.A + dummyzero
248 | C = self.C + dummyzero
249 | D = self.D + dummyzero
250 | Gamma = self.Gamma + dummyzero
251 | zeta_1 = zeta1( Gamma_hat, Delta)
252 | zeta_2 = zeta2( Gamma_hat, Delta)
253 | EE = 1 - Gamma_hat * zeta_2
254 |
255 | if v0 is None:
256 | #v0 = torch.randn_like(y0) * D / 2 ** 0.5
257 | v0 = (C - A * y0)/Gamma**0.5
258 |
259 | # Calculate mean position and velocity
260 | term1 = (1 - zeta_1) * (C * t - A * t * y0) + zeta_2 * (Gamma ** 0.5) * v0 * t
261 | y_mean = term1 + y0
262 | v_mean = (1 - EE)*(C - A * y0) / (Gamma ** 0.5) + (EE - A * t * (1 - zeta_1)) * v0
263 |
264 | cov_yy = D**2 * t * self.sig22(Gamma_hat, Delta)
265 | cov_vv = D**2 * self.sig11(Gamma_hat, Delta) / 2
266 | cov_yv = (zeta2(Gamma_hat, Delta) * Gamma_hat * D ) **2 / 2 / (Gamma ** 0.5)
267 |
268 | # sample new position and velocity with multivariate normal distribution
269 |
270 | batch_shape = y0.shape
271 | cov_matrix = torch.zeros(*batch_shape, 2, 2, device=y0.device, dtype=y0.dtype)
272 | cov_matrix[..., 0, 0] = cov_yy
273 | cov_matrix[..., 0, 1] = cov_yv
274 | cov_matrix[..., 1, 0] = cov_yv # symmetric
275 | cov_matrix[..., 1, 1] = cov_vv
276 |
277 | # Sample correlated noise from multivariate normal
278 | mean = torch.zeros(*batch_shape, 2, device=y0.device, dtype=y0.dtype)
279 | mean[..., 0] = y_mean
280 | mean[..., 1] = v_mean
281 | new_yv = torch.distributions.MultivariateNormal(
282 | loc=mean,
283 | covariance_matrix=cov_matrix
284 | ).sample()
285 |
286 | return new_yv[...,0], new_yv[...,1]
287 |
288 |
289 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | """Unit test package for LanPaint."""
2 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 |
4 | # Add the project root directory to Python path
5 | # This allows the tests to import the project
6 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
7 |
--------------------------------------------------------------------------------
/tests/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | testpaths = . # Run tests in the current directory
3 | python_files = test_*.py # Run tests in files that start with "test_"
4 | norecursedirs = .. # Don't run tests in the parent directory
5 |
--------------------------------------------------------------------------------
/tests/test_LanPaint.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """Tests for `LanPaint` package."""
4 |
5 | import pytest
6 | from src.LanPaint.nodes import Example
7 |
8 | @pytest.fixture
9 | def example_node():
10 | """Fixture to create an Example node instance."""
11 | return Example()
12 |
13 | def test_example_node_initialization(example_node):
14 | """Test that the node can be instantiated."""
15 | assert isinstance(example_node, Example)
16 |
17 | def test_return_types():
18 | """Test the node's metadata."""
19 | assert Example.RETURN_TYPES == ("IMAGE",)
20 | assert Example.FUNCTION == "test"
21 | assert Example.CATEGORY == "Example"
22 |
--------------------------------------------------------------------------------
/web/js/example.js:
--------------------------------------------------------------------------------
1 | console.log(app);
2 |
--------------------------------------------------------------------------------