dikdimon commited on
Commit
999c747
·
verified ·
1 Parent(s): 7f2f13f

Upload sd-webui-negpip using SD-Hub

Browse files
sd-webui-negpip/.github/FUNDING.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github:[hako-mikan] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4
+ patreon: # Replace with a single Patreon username
5
+ open_collective: # Replace with a single Open Collective username
6
+ ko_fi: # Replace with a single Ko-fi username
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: # Replace with a single Liberapay username
10
+ issuehunt: # Replace with a single IssueHunt username
11
+ otechie: # Replace with a single Otechie username
12
+ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13
+ custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
sd-webui-negpip/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
sd-webui-negpip/README.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NegPiP - Negative Prompt in Prompt
2
+ [<img src="https://img.shields.io/badge/lang-Egnlish-blue.svg?style=plastic" height="25" />](README.md)
3
+ [<img src="https://img.shields.io/badge/言語-日本語-green.svg?style=plastic" height="25" />](README_jp.md)
4
+ [<img src="https://img.shields.io/badge/语言-中文-red.svg?style=plastic" height="25" />](README_cn.md)
5
+ [<img src="https://img.shields.io/badge/Support-%E2%99%A5-magenta.svg?logo=github&style=plastic" height="25" />](https://github.com/sponsors/hako-mikan)
6
+
7
+
8
+ Extension for Stable Diffusion web-ui enables negative prompt in prompt
9
+
10
+ ## Update 2025.11.30.0100(JST)
11
+ - support Z-Image in Forge NEO
12
+
13
+ ## Update 2023.10.29.2100(JST)
14
+ - Option to hide this extention in t2i/i2i tab [Detail](#hide-this-extention-in-text2imgimg2img-tab),[詳細](README_jp.md#txt2imgimg2imgタブで拡張を表示しない),[解释](README_cn.md#在txt2imgimg2img标签中不显示扩展)
15
+
16
+ ### [For users of ADetailer](#for-users-of-adetailer)/[ADetailerとの併用について](README_jp.md#adetailerとの併用について)/[关于与ADetailer的同时使用](README_cn.md#关于与adetailer的同时使用)
17
+
18
+ # Overview
19
+ This extension enhances the stable diffusion web-ui prompts and cross-attention, allowing for the use of prompts with negative effects within regular prompts and prompts with positive effects within negative prompts. Typically, unwanted elements are placed in negative prompts, but negative prompts may not always have a significant impact in calculations. With this extension, it becomes possible to use negative prompts with effects comparable to regular prompts. This enables stronger effects even for words that might have collapsed when their values were increased too much in negative prompts before, by incorporating negative effects into the prompts.
20
+
21
+ # Instructions
22
+ By checking the "Active" box, it will become effective. In the prompt input screen, entering a negative value like `(word:-1)` will give it a negative effect. It also works with negative prompts, in which case it will have a positive effect.
23
+
24
+ This was created with the prompt "gothic dress". Despite including `(black:1.8)` in the negative prompt, it's still black. It seems impossible to completely eliminate the blackness of word `gothic`.
25
+
26
+ ![image1](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample.jpg)
27
+
28
+ Following image created using `(black:-1.8)` in the prompt with NegPiP. It's no longer black.
29
+
30
+ ![image2](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample2.jpg)
31
+
32
+ By the way, this is what happens when you don't use either NegPiP or negative prompts.
33
+ ![image2](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample3.jpg)
34
+
35
+ ## Magical Dandy
36
+ Magical Dandy is a magical dandy. Summoning a magical dandy is very difficult. That's because it requires coexistence of a magical girl and a dandy. But the dandy is weak. The girl is strong. Very strong. So the dandy ends up losing. Even if you put `(girl:1.8)` in the negative prompt, it won't come up.
37
+ ![](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample4.jpg)
38
+
39
+ Therefore, it may be necessary to input `(girl:-1.6)` in the prompt to remove the girl.
40
+ ![](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample5.jpg)
41
+
42
+ ## Hide this extention in text2img/img2img tab
43
+ In the Web-UI, go to Settings > NegPiP.
44
+ Check the "Hide in Hide in Txt2Img/Img2Img tab" option.
45
+ If you check this, the "Active" in Settings will be effective.
46
+
47
+ ## How to Use via API
48
+ The following format is used when utilizing this extension via the API.
49
+
50
+ ```
51
+ "alwayson_scripts": {
52
+ "NegPiP": {
53
+ "args": [True]
54
+ }}
55
+ ```
56
+
57
+ ## For users of ADetailer
58
+ In the Web-UI, go to Settings > ADetailer.
59
+ Add ",negpip" to the end of the text box labeled "Script names to apply to ADetailer (separated by comma)"
60
+ Click "Apply Settings.
61
+
62
+ ### Update 2023.09.05.2000(JST)
63
+ - Prompt Edittingに対応
64
+ - Regional Prompterに対応(最新版のRegional Prompterが必要)
65
+ - 負の値を入れていないときでも有効化したときに生成結果が変わる問題を修正
66
+
67
+ - Supports Prompt Editing
68
+ - Supports Regional Prompter (latest version of Regional Prompter required)
69
+ - Fixed the issue where generated results change even when negative values are not entered
70
+
71
+ - 支持Prompt Editting
72
+ - 支持区Regional Prompter(需要最新版Regional Prompter)
73
+ - 修复了即使没有输入负值时激活也会改变生成结果的问题
74
+
sd-webui-negpip/README_cn.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NegPiP - Negative Prompt in Prompt
2
+ [<img src="https://img.shields.io/badge/lang-Egnlish-blue.svg?style=plastic" height="25" />](README.md)
3
+ [<img src="https://img.shields.io/badge/言語-日本語-green.svg?style=plastic" height="25" />](README_jp.md)
4
+ [<img src="https://img.shields.io/badge/语言-中文-red.svg?style=plastic" height="25" />](README_cn.md)
5
+ [<img src="https://img.shields.io/badge/Support-%E2%99%A5-magenta.svg?logo=github&style=plastic" height="25" />](https://github.com/sponsors/hako-mikan)
6
+
7
+
8
+ 在 SD WebUI 中允许使用反向咒语(提示词)
9
+
10
+ # 摘要
11
+ 该扩展增强了 SD WebUI 的 提示 和 交叉注意力 功能,允许在常规咒语中使用反向咒语,在反向咒语中使用正向咒语。通常情况下,不需要的元素会被放置在反向咒语中,但反向咒语在计算中不一定会产生重大影响。有了这一扩展,就可以使用效果与常规咒语相当的反向咒语。通过在咒语中加入反向效果,即使是以前在反向咒语中数值增加过多而可能崩溃的咒语,也能获得更强的效果。
12
+
13
+ # 使用
14
+ 选中“Active”复选框后,该插件将生效。在提示词输入框中,输入负值(如`(word:-1)`)时会产生反向作用。它也适用于反向咒语,在这种情况下,它将产生正向效应。
15
+
16
+ 这是根据“gothic dress”的提示创建的。尽管在否定提示中包含了`(black:1.8)`,但它仍然是黑色的。要完全消除`gothic`一词的黑色似乎是不可能的。
17
+
18
+ ![image1](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample.jpg)
19
+
20
+ 下图在 NegPiP 中使用`(black:-1.8)`创建,不再是黑色。
21
+
22
+ ![image2](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample2.jpg)
23
+
24
+ 顺带一提,这是不使用 NegPiP 或负面提示时的结果。
25
+ ![image2](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample3.jpg)
26
+
27
+ ## 魔法花公
28
+ 魔法花公就是带有花花公子属性的魔法少男,但是想要召唤他异常困难。这是因为它需要魔法少女(magical girl)和花花公子(dandy)共存。但dandy属性却很弱。girl属性很坚强。非常强。所以,dandy最终还是输了。即使在反向中输入`(girl:1.8)`,花花公子也还算是不会出现。
29
+ ![](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample4.jpg)
30
+
31
+ 因此,可能有必要在正向咒语中输入`(girl:-1.6)`来削弱 girl。
32
+ ![](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample5.jpg)
33
+
34
+ ## 在Txt2Img/Img2Img标签中不显示扩展
35
+ 在Web-UI中,转到Settings > NegPiP。
36
+ 勾选"Hide in Hide in Txt2Img/Img2Img tab"选项。
37
+ 如果您勾选此选项,Settings中的"Active"将生效。
38
+
39
+ ## 通过 API 使用的方法
40
+ 通过 API 使用此扩展时,使用以下格式。
41
+ ```
42
+ "alwayson_scripts": {
43
+ "NegPiP": {
44
+ "args": [True]
45
+ }}
46
+ ```
47
+
48
+ ## 关于与ADetailer的同时使用
49
+ 在Web-UI中,前往“Settings” > “ADetailer”。
50
+ 在标有"Script names to apply to ADetailer (separated by comma)"”的文本框末尾添加“,negpip”。
51
+ 点击“Apply Settings”。
sd-webui-negpip/README_jp.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NegPiP - Negative Prompt in Prompt
2
+ [<img src="https://img.shields.io/badge/lang-Egnlish-blue.svg?style=plastic" height="25" />](README.md)
3
+ [<img src="https://img.shields.io/badge/言語-日本語-green.svg?style=plastic" height="25" />](README_jp.md)
4
+ [<img src="https://img.shields.io/badge/语言-中文-red.svg?style=plastic" height="25" />](README_cn.md)
5
+ [<img src="https://img.shields.io/badge/Support-%E2%99%A5-magenta.svg?logo=github&style=plastic" height="25" />](https://github.com/sponsors/hako-mikan)
6
+
7
+
8
+ 負の効果を持つプロンプトを使えるようになります
9
+
10
+ # 概要
11
+ この拡張は、stable diffusion web-uiのプロンプトおよびクロスアテンションを拡張して、負の効果を持つプロンプトをプロンプト内で、正の効果を持つプロンプトをネガティブプロンプト内で使用できるようにします。通常、描きたくないものはネガティブプロンプトに書かれますが、ネガティブプロンプトの計算上、あまり効果が現れないことがあります。この拡張では、プロンプトと同程度の効果を持つ負のプロンプトを使用できるようにします。これにより、以前はネガティブプロンプトに置いて値を大きくしすぎて崩壊していたような単語でも、プロンプトに負の効果を持たせることができ、より強い効果が期待できます。
12
+
13
+ # 使い方
14
+ Activeにチェックを入れることで有効になります。プロンプト入力画面において (word:-1)のようにマイナスの値を入れることで負の効果を持つようになります。ネガティブプロンプトでも有効で、この場合は正の効果を持ちます。値は1より大きな値を入力しないと効果が現れない場合があります。
15
+
16
+ これはgothic dressというプロンプトで作りました。ネガティブプロンプトに`(black:1.8)`と入れているにもかかわらず黒いですね。gothicの黒を消しきれないです。
17
+ ![image1](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample.jpg)
18
+
19
+ これはNegPiPでプロンプトに`(black:-1.8)`を入れました。黒くなくなりましたね。
20
+ ![image2](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample2.jpg)
21
+
22
+ ちなみに、NegPiPもネガティブプロンプトも使わないとこうなります。
23
+ ![image3](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample3.jpg)
24
+
25
+ ## マジカルダンディ
26
+ マジカルダンディはマジカルなダンディです。マジカルなダンディを呼び出すことはとても難しいです。それはmagical girlとdandyを共存させる必要があるからです。でもダンディは弱いです。girlは強いです。とても強いです。なのでダンディは負けてしまいます。ネガティブプロンプトに`(girl:1.8)`って入れても出てきません。
27
+ ![](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample4.jpg)
28
+
29
+ なのでプロンプトの方に`(girl:-1.6)`と入れてgirlを消す必要があるんじゃんよ。
30
+ ![](https://github.com/hako-mikan/sd-webui-negpip/blob/imgs/sample5.jpg)
31
+
32
+ ## Txt2Img/Img2Imgタブで拡張を表示しない
33
+ Web-UIで、Settings > NegPiPに移動します。
34
+ "Hide in Hide in Txt2Img/Img2Img tab"のオプションをチェックしてください。
35
+ これをチェックすると、Settingsの"Active"が有効になります。
36
+
37
+ ## APIで有効化する
38
+ スクリプトの指定を以下のように記述してください。
39
+
40
+ ```
41
+ "alwayson_scripts": {
42
+ "NegPiP": {
43
+ "args": [True]
44
+ }}
45
+ ```
46
+
47
+ ## ADetailerとの併用について
48
+ Web-UIで、Settings > ADetailerに移動してください。
49
+ 「Script names to apply to ADetailer (separated by comma)」と書かれたテキストボックスの末尾に「,negpip」を追加し、Apply Settings
50
+
51
+
sd-webui-negpip/javascript/inputAccordion_m.js ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function setupAccordion_m(accordion) {
2
+ // 既に処理済みの場合はスキップ
3
+ if (accordion.getAttribute('data-processed') === 'true') {
4
+ return;
5
+ }
6
+ accordion.setAttribute('data-processed', 'true'); // 処理済みフラグを追加
7
+
8
+ var labelWrap = accordion.querySelector('.label-wrap');
9
+ var gradioCheckbox = gradioApp().querySelector('#' + accordion.id + "-checkbox input");
10
+ var extra = gradioApp().querySelector('#' + accordion.id + "-extra");
11
+ var span = labelWrap.querySelector('span');
12
+
13
+ // 初期状態をGradioの状態に基づいて設定
14
+ var visibleCheckbox = document.createElement('INPUT');
15
+ visibleCheckbox.type = 'checkbox';
16
+ visibleCheckbox.checked = gradioCheckbox.checked; // Gradioの初期状態を継承
17
+ visibleCheckbox.id = accordion.id + "-visible-checkbox";
18
+ visibleCheckbox.className = gradioCheckbox.className + " input-accordion-checkbox";
19
+
20
+ // 既にチェックボックスが存在していないか確認して追加
21
+ if (!span.querySelector(`#${visibleCheckbox.id}`)) {
22
+ span.insertBefore(visibleCheckbox, span.firstChild);
23
+ }
24
+
25
+ accordion.visibleCheckbox = visibleCheckbox;
26
+
27
+ if (extra) {
28
+ labelWrap.insertBefore(extra, labelWrap.lastElementChild);
29
+ }
30
+
31
+ // チェックボックスクリック時のイベント
32
+ visibleCheckbox.addEventListener('click', function(event) {
33
+ event.stopPropagation(); // クリックイベントの伝播を停止
34
+ console.log(`Checkbox in accordion ${accordion.id} is now: `, visibleCheckbox.checked);
35
+
36
+ // Gradioのチェックボックス状態を更新
37
+ gradioCheckbox.checked = visibleCheckbox.checked;
38
+ gradioCheckbox.dispatchEvent(new Event('input', { bubbles: true }));
39
+ });
40
+
41
+ // Gradioチェックボックスの変更を監視して表示用チェックボックスを更新
42
+ var observer = new MutationObserver(function(mutations) {
43
+ mutations.forEach(function(mutation) {
44
+ visibleCheckbox.checked = gradioCheckbox.checked;
45
+ console.log(`Visible checkbox in accordion ${accordion.id} updated to: `, visibleCheckbox.checked);
46
+ });
47
+ });
48
+
49
+ observer.observe(gradioCheckbox, { attributes: true, attributeFilter: ['checked'] });
50
+ }
51
+
52
+ onUiLoaded(function() {
53
+ for (var accordion of gradioApp().querySelectorAll('.input-accordion-m')) {
54
+ setupAccordion_m(accordion);
55
+ }
56
+ });
sd-webui-negpip/scripts/__pycache__/negpip_v2_finals.cpython-310.pyc ADDED
Binary file (38.2 kB). View file
 
sd-webui-negpip/scripts/negpip_v2_finals.py ADDED
@@ -0,0 +1,1418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ # ══════════════════════════════════════════════════════════════════════════════
3
+ # NegPiP — Negative Prompt in Positive (plan-based appended NegPiP v2)
4
+ #
5
+ # Architecture summary
6
+ # ────────────────────
7
+ # This is plan-based appended NegPiP v2. It is NOT a v3 true token-level
8
+ # / embedding-level rewrite. What that means:
9
+ #
10
+ # v2 (this file):
11
+ # - NegPiP targets are re-encoded as separate conditioning tensors
12
+ # - those tensors are APPENDed to the context before attention
13
+ # - NegpipSpan / NegpipRegionPlan describe exactly which appended tokens
14
+ # belong to which target, so per-target V inversion is precise
15
+ # - _current_negpip_plan is set in sub_forward for every call to
16
+ # main_forward so cond/uncond branches always use the right plan
17
+ # - NEGPIP_USE_V2 = False falls back to v1 rev2 behaviour globally
18
+ #
19
+ # v3 (future, separate task):
20
+ # - no append-conditioning architecture
21
+ # - sign-aware manipulation inside the base context token encoding
22
+ # - exact in-base-context token spans
23
+ # - deeper integration by analogy with ComfyUI-ppm
24
+ #
25
+ # Extraction pipeline (from v1 rev2, preserved here):
26
+ # Phase A — _strip_negpip_from_original() called ONCE per prompt, on the
27
+ # original (un-normalised) text, before the step loop.
28
+ # Phase B — _find_negpip_segments() called per-step on schedule
29
+ # strings; adds targets to textweights WITHOUT removal gate so
30
+ # scheduled prompts never lose targets on repeated steps.
31
+ #
32
+ # Compatibility matrix (all paths preserved):
33
+ # classic SD1.5 / SDXL → _ClassicBackend + hook_forwards
34
+ # Forge Flux → _FluxBackend + hook_forwards_f
35
+ # Forge ZImage / Lumina → _ZImageBackend + hook_forwards_z
36
+ # Regional Prompter → enable_rp_latent + region_index=self.latenti
37
+ # ══════════════════════════════════════════════════════════════════════════════
38
+ import torch
39
+ import re
40
+ import json
41
+ from torch import nn, einsum
42
+ from einops import rearrange, repeat
43
+ from inspect import isfunction
44
+ from modules.ui import versions_html
45
+ from packaging import version
46
+ from functools import wraps
47
+
48
+ # ══════════════════════════════════════════════════════════════════════════════
49
+ # v2 data model
50
+ # ══════════════════════════════════════════════════════════════════════════════
51
+ from dataclasses import dataclass, field
52
+ from typing import Optional, List
53
+ import warnings as _warnings
54
+
55
+ # Feature flag — set to False to fall back to v1 behaviour globally.
56
+ NEGPIP_USE_V2: bool = True
57
+
58
+ @dataclass
59
+ class NegpipSpan:
60
+ """
61
+ Describes one target's token range within the APPENDED NegPiP conditioning.
62
+
63
+ ``token_offset`` counts from the END of the appended block, in tokens.
64
+ ``token_count`` is the number of tokens occupied by this target.
65
+ ``sign`` is applied to V for this span (-1.0 for standard NegPiP).
66
+
67
+ Example: two targets appended as [T1-tokens | T2-tokens]:
68
+ T2: NegpipSpan(token_offset=0, token_count=len_T2, sign=-1)
69
+ T1: NegpipSpan(token_offset=len_T2, token_count=len_T1, sign=-1)
70
+ """
71
+ token_offset: int
72
+ token_count: int
73
+ sign: float = -1.0
74
+
75
+ @dataclass
76
+ class NegpipRegionPlan:
77
+ """
78
+ Fully describes the NegPiP conditioning appended for ONE region at ONE step.
79
+
80
+ Replaces the raw ``(cond_tensor, n_tokens)`` tuple returned by conddealer.
81
+ ``spans`` provides per-target metadata so attention can do precise,
82
+ per-span V inversion rather than a single blanket operation.
83
+ """
84
+ region_pad: int = 0
85
+ cond_tensor: Optional[object] = None # torch.Tensor | None
86
+ spans: List[NegpipSpan] = field(default_factory=list)
87
+ total_tokens: int = 0
88
+
89
+ def to_legacy(self):
90
+ """Return (cond_tensor, total_tokens) for v1-fallback paths."""
91
+ return self.cond_tensor, self.total_tokens
92
+
93
+
94
+ # ══════════════════════════════════════════════════════════════════════════════
95
+ # Backend adapters
96
+ # ══════════════════════════════════════════════════════════════════════════════
97
+
98
+ class _NegpipBackendBase:
99
+ """
100
+ Thin interface isolating backend-specific conditioning logic.
101
+
102
+ Subclasses implement encode_target() for their backend.
103
+ The returned (cond_data_tensor, raw_tokenlen) is consumed by
104
+ _encode_negpip_plan() which then builds NegpipRegionPlan.
105
+ """
106
+ def encode_target(self, text: str, abs_weight: float, sd_model, p):
107
+ """
108
+ Encode ONE NegPiP target.
109
+
110
+ Returns (cond_data, tokenlen) where:
111
+ cond_data — raw conditioning tensor (before slicing / padding)
112
+ tokenlen — token count for 'text' alone (no BOS/EOS)
113
+ """
114
+ raise NotImplementedError
115
+
116
+ def slice_cond(self, cond_data, tokenlen: int, isxl: bool, cond_key: str):
117
+ """
118
+ Slice cond_data to the relevant token range for this backend.
119
+ Default: SD/SDXL behaviour (1:tokenlen+2 rows, skipping BOS/EOS).
120
+ """
121
+ if isxl:
122
+ return cond_data[cond_key][1:tokenlen + 2, :]
123
+ return cond_data[1:tokenlen + 2, :]
124
+
125
+
126
+ class _ClassicBackend(_NegpipBackendBase):
127
+ """A1111 classic / Forge classic."""
128
+ def __init__(self, tokenizer, isxl: bool, cond_key: str, batch: int):
129
+ self.tokenizer = tokenizer
130
+ self.isxl = isxl
131
+ self.cond_key = cond_key
132
+ self.batch = batch
133
+
134
+ def encode_target(self, text, abs_weight, sd_model, p):
135
+ from modules import devices, prompt_parser
136
+ inp = SdConditioning([f"({text}:{abs_weight})"], width=p.width, height=p.height)
137
+ with devices.autocast():
138
+ cond = prompt_parser.get_learned_conditioning(sd_model, inp, p.steps)
139
+ cond_data = cond[0][0].cond
140
+ _, tokenlen = self.tokenizer(text)
141
+ return cond_data, tokenlen
142
+
143
+ def slice_cond(self, cond_data, tokenlen, isxl, cond_key):
144
+ if isxl:
145
+ return cond_data[cond_key][1:tokenlen + 2, :]
146
+ return cond_data[1:tokenlen + 2, :]
147
+
148
+
149
+ class _FluxBackend(_NegpipBackendBase):
150
+ """Forge Flux."""
151
+ def __init__(self, tokenizer, cond_key: str, batch: int):
152
+ self.tokenizer = tokenizer
153
+ self.cond_key = cond_key
154
+ self.batch = batch
155
+
156
+ def encode_target(self, text, abs_weight, sd_model, p):
157
+ from modules import devices, prompt_parser
158
+ inp = SdConditioning([f"({text}:{abs_weight})"], width=p.width, height=p.height)
159
+ with devices.autocast():
160
+ cond = prompt_parser.get_learned_conditioning(sd_model, inp, p.steps)
161
+ cond_data = cond[0][0].cond
162
+ _, tokenlen = self.tokenizer(text)
163
+ return cond_data, tokenlen
164
+
165
+ def slice_cond(self, cond_data, tokenlen, isxl, cond_key):
166
+ return cond_data[cond_key][0:tokenlen + 1, :]
167
+
168
+
169
+ class _ZImageBackend(_NegpipBackendBase):
170
+ """Forge ZImage / Lumina."""
171
+ def __init__(self, tokenizer, batch: int):
172
+ self.tokenizer = tokenizer
173
+ self.batch = batch
174
+
175
+ def encode_target(self, text, abs_weight, sd_model, p):
176
+ from modules import devices, prompt_parser
177
+ inp = SdConditioning([f"({text}:{abs_weight})"], width=p.width, height=p.height)
178
+ with devices.autocast():
179
+ cond = prompt_parser.get_learned_conditioning(sd_model, inp, p.steps)
180
+ cond_data = cond[0][0].cond
181
+ _, tokenlen = self.tokenizer(text)
182
+ return cond_data, tokenlen
183
+
184
+ def slice_cond(self, cond_data, tokenlen, isxl, cond_key):
185
+ # ZImage: skip first 3 and last 5 special tokens
186
+ return cond_data[3:-5, :]
187
+
188
+
189
+ def _apply_negpip_spans(v_tensor, plan: NegpipRegionPlan) -> None:
190
+ """
191
+ Apply per-span V inversion in-place using a NegpipRegionPlan.
192
+
193
+ v_tensor shape: (batch*heads, seq_len, head_dim) [main_forward2]
194
+ or (batch, seq_len, dim) [main_forward]
195
+
196
+ The NegPiP conditioning block is APPENDED to the context, so the
197
+ last ``plan.total_tokens`` positions in seq_len belong to NegPiP.
198
+ Within that block, each NegpipSpan tracks offset-from-end and count.
199
+ """
200
+ if not plan.spans or plan.total_tokens == 0:
201
+ return
202
+ total = plan.total_tokens
203
+ for span in plan.spans:
204
+ if span.token_count <= 0:
205
+ continue
206
+ # Absolute positions from the end of v_tensor (seq dimension = dim 1):
207
+ # end_pos = -(span.token_offset) or None if offset == 0
208
+ # start_pos = -(span.token_offset + span.token_count)
209
+ end_pos = -span.token_offset if span.token_offset > 0 else None
210
+ start_pos = -(span.token_offset + span.token_count)
211
+ if end_pos is not None:
212
+ v_tensor[:, start_pos:end_pos, :] *= span.sign
213
+ else:
214
+ v_tensor[:, start_pos:, :] *= span.sign
215
+
216
+
217
+ classic = forge = reforge = False
218
+ try:
219
+ import ldm.modules.attention as atm
220
+ forge = False
221
+ except:
222
+ #forge
223
+ try:
224
+ from backend.diffusion_engine.base import ForgeDiffusionEngine, ForgeObjects
225
+ from backend.nn.flux import attention, fp16_fix
226
+ forge = True
227
+ except:
228
+ classic = True
229
+
230
+ reforge = "reForge" in versions_html()
231
+
232
+ import torch.nn.functional as F
233
+ import modules.ui
234
+ import modules
235
+ from modules import prompt_parser, devices
236
+ from modules import shared
237
+ from modules.script_callbacks import CFGDenoiserParams, on_cfg_denoiser, on_ui_settings
238
+
239
+ debug = False
240
+ debug_p = False
241
+
242
+ OPT_ACT = "negpip_active"
243
+ OPT_HIDE = "negpip_hide"
244
+
245
+ NEGPIP_T = "customscript/negpip.py/txt2img/Active/value"
246
+ NEGPIP_I = "customscript/negpip.py/img2img/Active/value"
247
+ CONFIG = shared.cmd_opts.ui_config_file
248
+
249
+ try:
250
+ with open(CONFIG, 'r', encoding="utf-8") as json_file:
251
+ ui_config = json.load(json_file)
252
+ except Exception:
253
+ ui_config = {}
254
+
255
+ startup_t = ui_config[NEGPIP_T] if NEGPIP_T in ui_config else None
256
+ startup_i = ui_config[NEGPIP_I] if NEGPIP_I in ui_config else None
257
+ active_t = "Active" if startup_t else "Not Active"
258
+ active_i = "Active" if startup_i else "Not Active"
259
+
260
+ opt_active = getattr(shared.opts,OPT_ACT, True)
261
+ opt_hideui = getattr(shared.opts,OPT_HIDE, False)
262
+
263
+ # ──────────────────────────────────────────────────────────────────────────────
264
+ # NegPiP extraction: structural bracket-aware scanner
265
+ #
266
+ # Why not regex?
267
+ # The old minusgetter regex r'\(([^(:)]*):...\)' breaks on:
268
+ # - scientific notation: (cat:-1e-3) — [^(:)]* stops at 'e'
269
+ # - nested emphasis: (red (glowing eyes):-1.4) — [^(:]* refuses '('
270
+ #
271
+ # The new approach scans matching parentheses structurally,
272
+ # then checks if the content ends with :−NUMBER.
273
+ # This is O(n) and handles arbitrary nesting depth.
274
+ #
275
+ # LEGACY fallback regex (kept for reference; no longer used as primary path):
276
+ _LEGACY_MINUSGETTER = r'\(([^(:)]*):\s*-[\d]+(\.[/\d]+)?(?:\s*)\)'
277
+
278
+ def _find_negpip_segments(prompt: str) -> list:
279
+ """
280
+ Structural NegPiP extractor.
281
+
282
+ Scans ``prompt`` for all top-level ``(inner : -NUMBER)`` constructs,
283
+ where inner may itself contain nested parentheses (e.g. emphasis).
284
+
285
+ Returns a list of tuples:
286
+ (start: int, end: int, inner: str, weight: float)
287
+
288
+ where [start:end] is the full span including outer parens,
289
+ ``inner`` is the raw text before the colon, and ``weight`` is the
290
+ (negative) float.
291
+
292
+ Scientific notation (1e-3, 1E+2, …) and leading-dot numbers (-.5)
293
+ are all supported.
294
+
295
+ Edge cases:
296
+ - weight == 0 or -0.0 → not treated as NegPiP, skipped
297
+ - BREAK token → no parens, never matched
298
+ - Positive weights → weight > 0, skipped by caller
299
+ """
300
+ results = []
301
+ i = 0
302
+ n = len(prompt)
303
+ # Regex for the LAST colon + negative number inside bracket content.
304
+ # re.DOTALL so '.' matches newlines in pathological inputs.
305
+ _tail = re.compile(
306
+ r'^(.*?):\s*'
307
+ r'(-(?:\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?))'
308
+ r'\s*$',
309
+ re.DOTALL,
310
+ )
311
+ while i < n:
312
+ if prompt[i] != '(':
313
+ i += 1
314
+ continue
315
+ # Walk forward tracking bracket depth
316
+ depth = 1
317
+ j = i + 1
318
+ while j < n and depth > 0:
319
+ c = prompt[j]
320
+ if c == '(':
321
+ depth += 1
322
+ elif c == ')':
323
+ depth -= 1
324
+ j += 1
325
+ # prompt[i:j] is the full "(…)" span; content is without outer parens
326
+ content = prompt[i + 1: j - 1]
327
+ m = _tail.match(content)
328
+ if m:
329
+ weight = float(m.group(2))
330
+ if weight < 0: # strict negative only
331
+ results.append((i, j, m.group(1), weight))
332
+ i = j
333
+ return results
334
+
335
+ def _strip_negpip_from_original(prompt: str) -> str:
336
+ """
337
+ Remove all NegPiP segments from the ORIGINAL (pre-parser) prompt string.
338
+
339
+ Must be called ONCE per prompt, before the per-step schedule loop.
340
+ Uses _find_negpip_segments on the original text so that un-normalised
341
+ forms like (red (glowing eyes):-1.4) are found and removed correctly —
342
+ not the v21-normalised schedule form which may differ in number format
343
+ or nested-emphasis structure.
344
+
345
+ Spans are removed in reverse order so earlier indices remain valid.
346
+ """
347
+ segs = _find_negpip_segments(prompt)
348
+ if not segs:
349
+ return prompt
350
+ chars = list(prompt)
351
+ for start, end, _inner, _w in reversed(segs):
352
+ del chars[start:end]
353
+ return ''.join(chars)
354
+
355
+
356
+ COND_KEY_C = "crossattn"
357
+ COND_KEY_V = "vector"
358
+
359
+ class Script(modules.scripts.Script):
360
+ def __init__(self):
361
+ self.active = False
362
+ self.conds = None
363
+ self.unconds = None
364
+ self.conlen = []
365
+ self.unlen = []
366
+ self.contokens = []
367
+ self.untokens = []
368
+ self.hr = False
369
+ self.x = None
370
+
371
+ self.ipa = None
372
+
373
+ self.enable_rp_latent = False
374
+
375
+ def title(self):
376
+ return "NegPiP"
377
+
378
+ def show(self, is_img2img):
379
+ return modules.scripts.AlwaysVisible
380
+
381
+ infotext_fields = None
382
+ paste_field_names = []
383
+
384
+ def ui(self, is_img2img):
385
+ with InputAccordion(startup_i if is_img2img else startup_t, label=self.title(), visible = not opt_hideui) as active:
386
+ toggle = gr.Button(elem_id="switch_default", value=f"Toggle startup with Active(Now:{startup_i if is_img2img else startup_t}), Needs Restart to Apply", variant="primary")
387
+
388
+ def f_toggle(is_img2img):
389
+ key = NEGPIP_I if is_img2img else NEGPIP_T
390
+
391
+ # Safe read: if config file is missing, start with empty dict
392
+ try:
393
+ with open(CONFIG, 'r', encoding="utf-8") as json_file:
394
+ data = json.load(json_file)
395
+ except Exception:
396
+ data = {}
397
+
398
+ data[key] = not data.get(key, False)
399
+
400
+ # Safe write: create parent dir if needed
401
+ try:
402
+ import os
403
+ os.makedirs(os.path.dirname(CONFIG), exist_ok=True)
404
+ with open(CONFIG, 'w', encoding="utf-8") as json_file:
405
+ json.dump(data, json_file, indent=4)
406
+ except Exception as e:
407
+ print(f"[NegPiP] WARNING: could not write config: {e}")
408
+
409
+ return gr.update(value = f"Toggle startup Active(Now:{data[key]})")
410
+
411
+ toggle.click(fn=f_toggle,inputs=[gr.Checkbox(value = is_img2img, visible = False)],outputs=[toggle])
412
+
413
+ self.infotext_fields = [
414
+ (active, "NegPiP Active"),
415
+ ]
416
+
417
+ for _,name in self.infotext_fields:
418
+ self.paste_field_names.append(name)
419
+
420
+ return [active]
421
+
422
+ def process_batch(self, p, active,**kwargs):
423
+ self.__init__()
424
+ flag = False
425
+
426
+ if getattr(shared.opts,OPT_HIDE, False) and not getattr(shared.opts,OPT_ACT, False): return
427
+ elif not active: return
428
+
429
+ self.rpscript = None
430
+ #get infomation of regponal prompter
431
+ from modules.scripts import scripts_txt2img
432
+ for script in scripts_txt2img.alwayson_scripts:
433
+ if "rp.py" in script.filename:
434
+ self.rpscript = script
435
+
436
+ self.hrp, self.hrn = hr_dealer(p)
437
+
438
+ self.active = active
439
+ self.batch = p.batch_size
440
+ # old call, hasattr(shared.sd_model,"conditioner"), no longer works on forge backend, but forge backend provides its own way to do this.
441
+ self.isxl = p.sd_model.is_sdxl
442
+
443
+ # if you want to change other things to be more mnemonic to the current backend, here's the pprint calls i used to figure all this out in my initial port.
444
+ # lllyasviel should really document this stuff. it's a nice backend! but he hasn't told any of us how to use it.
445
+ #pprint(dir(p))
446
+ #pprint(dir(p.sd_model))
447
+ #pprint(dir(p.sd_model.forge_objects.unet))
448
+ #pprint(dir(p.sd_model.forge_objects.clip))
449
+ #pprint(dir(p.sd_model.forge_objects.clip.tokenizer))
450
+ #pprint(p.sd_model.is_sdxl)
451
+
452
+ self.rev = p.sampler_name in ["DDIM", "PLMS", "UniPC"]
453
+ if forge or reforge or classic: self.rev = not self.rev
454
+ self.modeltype = modeltype = "SD"
455
+
456
+ if forge:
457
+ if type(p.sd_model).__name__ == "ZImage":
458
+ tokenizer = p.sd_model.text_processing_engine_gemma.tokenize_line
459
+ self.modeltype = modeltype = "ZImage"
460
+ input = SdConditioning([""], width=p.width, height=p.height)
461
+ p.sd_model.text_processing_engine_gemma(input)
462
+ elif hasattr(p.sd_model, "text_processing_engine_l"):
463
+ tokenizer = p.sd_model.text_processing_engine_l.tokenize_line
464
+ else:
465
+ tokenizer = p.sd_model.text_processing_engine.tokenize_line
466
+ if "flux" in str(type(p.sd_model.forge_objects.unet.model.diffusion_model)):
467
+ self.modeltype = modeltype = "flux"
468
+
469
+ else:
470
+ tokenizer = shared.sd_model.conditioner.embedders[0].tokenize_line if self.isxl else shared.sd_model.cond_stage_model.tokenize_line
471
+
472
+ def _normalize_sep(text: str, seps) -> str:
473
+ """
474
+ Normalise Regional Prompter separator.
475
+
476
+ prompt_parser_fixed_v21 converts 'AND' -> '&' internally, so
477
+ schedule strings may arrive with '&' even when the RP script
478
+ reports seps='AND'. Normalise so split() always works.
479
+ """
480
+ if seps == "AND":
481
+ return text.replace(" & ", " AND ")
482
+ return text
483
+
484
+ def getshedulednegs(scheduled, prompts):
485
+ """
486
+ Extract NegPiP targets from prompt schedules.
487
+
488
+ v1-patch (rev2): architectural fix — strip and extract are now
489
+ SEPARATE operations with separate responsibilities.
490
+
491
+ Phase A — strip (called once per prompt, on the ORIGINAL):
492
+ _strip_negpip_from_original() scans the original (un-normalised)
493
+ prompt and removes all negpip spans. This is done before the
494
+ step loop so that:
495
+ - the original un-normalised form is found correctly, not a
496
+ v21-normalised schedule string
497
+ - subsequent steps do not attempt to re-strip an already-clean prompt
498
+
499
+ Phase B — extract (per step, from schedule string, no removal gate):
500
+ _find_negpip_segments() scans the schedule string for each step.
501
+ Targets are added to textweights REGARDLESS of whether Phase A
502
+ succeeded in removing them from the original. This fixes the
503
+ regression where scheduled targets were lost on repeated steps.
504
+
505
+ Fixes vs v1 rev1:
506
+ - nested emphasis (red (glowing eyes):-1.4) now ACTUALLY applied,
507
+ not silently skipped when v21 normalises the inner text
508
+ - [cat:(dog:-1):0.5] no longer loses target after the first step
509
+ - AND/& separator handled correctly for Regional Prompter
510
+ """
511
+ output = []
512
+ nonlocal flag
513
+
514
+ # ── Phase A: strip negpip spans from original prompts ONCE ────────
515
+ # We scan each original prompt (not a schedule string) so that
516
+ # the un-normalised form is used for removal. This runs before
517
+ # the step loop so repeated steps never try to re-strip.
518
+ for i in range(len(prompts)):
519
+ prompts[i] = _strip_negpip_from_original(prompts[i])
520
+
521
+ # ── Phase B: extract targets per step (no removal) ─────────────────
522
+ for i, batch_shedule in enumerate(scheduled):
523
+ stepout = []
524
+ seps = None
525
+ if self.rpscript:
526
+ if hasattr(self.rpscript, "seps"):
527
+ seps = self.rpscript.seps
528
+ self.enable_rp_latent = seps == "AND"
529
+
530
+ for step, prompt in batch_shedule:
531
+ # Normalise AND/& before splitting for Regional Prompter
532
+ prompt_norm = _normalize_sep(prompt, seps)
533
+ sep_prompts = prompt_norm.split(seps) if seps else [prompt_norm]
534
+
535
+ padd = 0
536
+ padtextweight = []
537
+ for sep_prompt in sep_prompts:
538
+ textweights = []
539
+
540
+ # Structural extraction from schedule string.
541
+ # textweights.append is NOT gated on removal —
542
+ # removal already happened in Phase A.
543
+ for _s, _e, inner, weight in _find_negpip_segments(sep_prompt):
544
+ text = inner.strip()
545
+ if text == "BREAK":
546
+ continue
547
+ textweights.append([text, weight])
548
+ flag = True
549
+
550
+ padtextweight.append([padd, textweights])
551
+ tokens, tokensnum = tokenizer(sep_prompt)
552
+ padd = tokensnum // 75 + 1 + padd
553
+
554
+ stepout.append([step, padtextweight])
555
+ output.append(stepout)
556
+ return output
557
+
558
+
559
+ scheduled_p = prompt_parser.get_learned_conditioning_prompt_schedules(p.prompts,p.steps)
560
+ scheduled_np = prompt_parser.get_learned_conditioning_prompt_schedules(p.negative_prompts,p.steps)
561
+
562
+ if self.hrp: scheduled_hr_p = prompt_parser.get_learned_conditioning_prompt_schedules(p.hr_prompts,p.hr_second_pass_steps if p.hr_second_pass_steps > 0 else p.steps)
563
+ if self.hrn: scheduled_hr_np = prompt_parser.get_learned_conditioning_prompt_schedules(p.hr_negative_prompts,p.hr_second_pass_steps if p.hr_second_pass_steps > 0 else p.steps)
564
+
565
+ nip = getshedulednegs(scheduled_p,p.prompts)
566
+ pin = getshedulednegs(scheduled_np,p.negative_prompts)
567
+
568
+ if self.hrp: hr_nip = getshedulednegs(scheduled_hr_p,p.hr_prompts)
569
+ if self.hrn: hr_pin = getshedulednegs(scheduled_hr_np,p.hr_negative_prompts)
570
+
571
+ cond_key = COND_KEY_C
572
+
573
+ # ── Build backend adapter ─────────────────────────────────────────
574
+ if NEGPIP_USE_V2:
575
+ if modeltype == "flux":
576
+ _backend = _FluxBackend(tokenizer, cond_key, self.batch)
577
+ elif modeltype == "ZImage":
578
+ _backend = _ZImageBackend(tokenizer, self.batch)
579
+ else:
580
+ _backend = _ClassicBackend(tokenizer, self.isxl, cond_key, self.batch)
581
+
582
+ def _encode_negpip_plan(region_pad: int, targets) -> NegpipRegionPlan:
583
+ """
584
+ v2 replacement for conddealer.
585
+
586
+ Encodes each target individually, tracks its token count as a
587
+ NegpipSpan, and assembles a NegpipRegionPlan.
588
+
589
+ Spans are ordered so that the FIRST target appended has the
590
+ highest offset-from-end (it's furthest from the V tail).
591
+
592
+ Falls back to legacy behaviour (NegpipRegionPlan wrapping the
593
+ old return values) if NEGPIP_USE_V2 is False.
594
+ """
595
+ if not NEGPIP_USE_V2:
596
+ # v1 fallback path — original conddealer logic
597
+ cond_t, n_tok = _conddealer_v1(targets)
598
+ plan = NegpipRegionPlan(region_pad=region_pad,
599
+ cond_tensor=cond_t,
600
+ total_tokens=n_tok if n_tok else 0)
601
+ if n_tok:
602
+ plan.spans = [NegpipSpan(token_offset=0, token_count=n_tok, sign=-1.0)]
603
+ return plan
604
+
605
+ slices = []
606
+ spans = []
607
+ running_offset = 0 # total tokens accumulated so far
608
+ strength_list = [] # for flux/ZImage strength array
609
+
610
+ for text, weight in targets:
611
+ abs_w = abs(weight)
612
+ try:
613
+ cond_data, tokenlen = _backend.encode_target(text, abs_w, shared.sd_model, p)
614
+ except Exception as exc:
615
+ print(f"[NegPiP v2] WARNING: failed to encode {text!r}: {exc}. Skipping.")
616
+ continue
617
+
618
+ slc = _backend.slice_cond(cond_data, tokenlen, self.isxl, cond_key)
619
+ actual_len = slc.shape[0]
620
+
621
+ slices.append(slc)
622
+ running_offset += actual_len
623
+
624
+ # Strength bookkeeping (flux/ZImage only)
625
+ if modeltype in ("flux", "ZImage"):
626
+ strength_list.extend([weight] * actual_len)
627
+
628
+ if not slices:
629
+ return NegpipRegionPlan(region_pad=region_pad)
630
+
631
+ # Build spans AFTER we know all lengths (offsets count from end)
632
+ # Rebuild running_offset from slice shapes in reverse:
633
+ total = sum(s.shape[0] for s in slices)
634
+ acc = 0
635
+ for slc in reversed(slices):
636
+ cnt = slc.shape[0]
637
+ spans.append(NegpipSpan(token_offset=acc, token_count=cnt, sign=-1.0))
638
+ acc += cnt
639
+ spans.reverse() # restore order (first target = highest offset)
640
+
641
+ # Assemble conditioning tensor
642
+ conds = torch.cat(slices, 0).unsqueeze(0).repeat(self.batch, 1, 1)
643
+
644
+ if modeltype in ("flux", "ZImage"):
645
+ self.strength = strength_list
646
+
647
+ return NegpipRegionPlan(
648
+ region_pad = region_pad,
649
+ cond_tensor = conds,
650
+ spans = spans,
651
+ total_tokens = total,
652
+ )
653
+
654
+ def _conddealer_v1(targets):
655
+ """Original conddealer logic, kept verbatim as v1 fallback."""
656
+ conds = []
657
+ start = None
658
+ end = None
659
+ if modeltype == "flux":
660
+ strength = []
661
+ for target in targets:
662
+ input = SdConditioning([f"({target[0]}:{-target[1]})"], width=p.width, height=p.height)
663
+ with devices.autocast():
664
+ cond = prompt_parser.get_learned_conditioning(shared.sd_model,input,p.steps)
665
+ cond_data = cond[0][0].cond
666
+ token, tokenlen = tokenizer(target[0])
667
+ conds.append(cond_data[cond_key][0:tokenlen + 1, :])
668
+ strength.extend([target[1]]*(cond_data.shape[0]))
669
+ conds = torch.cat(conds,0).unsqueeze(0)
670
+ conds = conds.repeat(self.batch,1,1)
671
+ self.strength = strength
672
+ return conds, conds.shape[1]
673
+ if modeltype == "ZImage":
674
+ strength = []
675
+ for target in targets:
676
+ input = SdConditioning([f"({target[0]}:{-target[1]})"], width=p.width, height=p.height)
677
+ with devices.autocast():
678
+ cond = prompt_parser.get_learned_conditioning(shared.sd_model,input,p.steps)
679
+ cond_data = cond[0][0].cond
680
+ conds.append(cond_data[3:-5, :])
681
+ strength.extend([target[1]]*(cond_data.shape[0]-8))
682
+ conds = torch.cat(conds,0).unsqueeze(0)
683
+ conds = conds.repeat(self.batch,1,1)
684
+ self.strength = strength
685
+ return conds, conds.shape[1]
686
+ for target in targets:
687
+ input = SdConditioning([f"({target[0]}:{-target[1]})"], width=p.width, height=p.height)
688
+ with devices.autocast():
689
+ cond = prompt_parser.get_learned_conditioning(shared.sd_model,input,p.steps)
690
+ cond_data = cond[0][0].cond
691
+ if start is None: start = cond_data[0:1, :] if not self.isxl else cond_data[cond_key][0:1, :]
692
+ if end is None: end = cond_data[-1:, :] if not self.isxl else cond_data[cond_key][-1:, :]
693
+ token, tokenlen = tokenizer(target[0])
694
+ conds.append(cond_data[1:tokenlen+2,:] if not self.isxl else cond_data[cond_key][1:tokenlen+2, :])
695
+ conds = torch.cat(conds, 0).unsqueeze(0)
696
+ return conds.repeat(self.batch,1,1), conds.shape[1]
697
+
698
+ def calcconds(targetlist):
699
+ """
700
+ v2: returns list of NegpipRegionPlan objects instead of
701
+ raw (tensor, n_tokens) tuples. Legacy .to_legacy() is
702
+ available on each plan for any code that needs the old format.
703
+ """
704
+ outconds = []
705
+ for batch in targetlist:
706
+ stepconds = []
707
+ for step, regions in batch:
708
+ regionplans = []
709
+ for region_pad, targets in regions:
710
+ if targets:
711
+ plan = _encode_negpip_plan(region_pad, targets)
712
+ else:
713
+ plan = NegpipRegionPlan(region_pad=region_pad)
714
+ regionplans.append(plan)
715
+ stepconds.append([step, regionplans])
716
+ outconds.append(stepconds)
717
+ return outconds
718
+
719
+ self.conds_all = calcconds(nip)
720
+ self.unconds_all = calcconds(pin)
721
+
722
+ if self.hrp: self.hr_conds_all = calcconds(hr_nip)
723
+ if self.hrn: self.hr_unconds_all = calcconds(hr_pin)
724
+
725
+ #print(self.conds_all)
726
+ #print(self.unconds_all)
727
+
728
+ resetpcache(p)
729
+
730
+ def calcsets(A, B):
731
+ return A // B if A % B == 0 else A // B + 1
732
+
733
+ # NOTE: conlen/unlen are computed from prompts[0] only.
734
+ # Heterogeneous batches (different prompt lengths per item) are a
735
+ # pre-existing limitation inherited from orig; not introduced by v2.
736
+ self.conlen = calcsets(tokenizer(p.prompts[0])[1],75)
737
+ self.unlen = calcsets(tokenizer(p.negative_prompts[0])[1],75)
738
+
739
+ if not flag:
740
+ self.active = False
741
+ unload(self,p)
742
+ return
743
+
744
+ if not hasattr(self,"negpip_dr_callbacks"):
745
+ self.negpip_dr_callbacks = on_cfg_denoiser(self.denoiser_callback)
746
+
747
+ #disable hookforward if hookfoward in regional prompter is eanble.
748
+ #negpip operation is treated in regional prompter
749
+
750
+ already_hooked = False
751
+ if self.rpscript is not None and hasattr(self.rpscript,"hooked"):already_hooked = self.rpscript.hooked
752
+
753
+ if not already_hooked:
754
+ if forge:
755
+ if modeltype == "flux":
756
+ self.handle = hook_forwards_f(self, p.sd_model.forge_objects.unet.model)
757
+ elif modeltype == "ZImage":
758
+ self.handle = hook_forwards_z(self, p.sd_model.forge_objects.unet.model)
759
+ else:
760
+ self.handle = hook_forwards(self, p.sd_model.forge_objects.unet.model)
761
+ else:
762
+ self.handle = hook_forwards(self, p.sd_model.model.diffusion_model)
763
+
764
+ def _plan_tokens(all_conds):
765
+ try:
766
+ plan = all_conds[0][0][1][0] # batch[0], step[0], regions[0]
767
+ return plan.total_tokens if isinstance(plan, NegpipRegionPlan) else plan[2]
768
+ except Exception:
769
+ return "?"
770
+ print(f"NegPiP enable, Positive:{_plan_tokens(self.conds_all)}, Negative:{_plan_tokens(self.unconds_all)}")
771
+
772
+ p.extra_generation_params.update({
773
+ "NegPiP Active":active,
774
+ })
775
+
776
+ def postprocess(self, p, processed, *args):
777
+ unload(self,p)
778
+ self.conds_all = None
779
+ self.unconds_all = None
780
+
781
+ def denoiser_callback(self, params: CFGDenoiserParams):
782
+ if debug: print("denoiser_callback",params.sampling_step, params.text_cond.shape)
783
+ if self.active:
784
+ if self.x is None: self.x = params.x.shape
785
+ if self.x != params.x.shape: self.hr = True
786
+
787
+ self.latenti = 0
788
+ # Cleanup: reset plan lists each callback so no stale state leaks
789
+ # between steps on exotic paths. They are repopulated below.
790
+ self._cond_plans = []
791
+ self._uncond_plans = []
792
+ # Keep Flux/ZImage plan aligned with the actual appended cond tensor.
793
+ self._flux_cond_plan = None
794
+ self._zimage_cond_plan = None
795
+
796
+ condslist = []
797
+ tokenslist = []
798
+ conds = self.hr_conds_all if self.hrp and self.hr else self.conds_all
799
+ if conds is not None:
800
+ for step, regions in conds[0]:
801
+ #print(" ", step,params.sampling_step)
802
+ if step >= params.sampling_step + 2:
803
+ for plan in regions:
804
+ # plan is NegpipRegionPlan; .to_legacy() for v1 compat
805
+ condslist.append(plan.cond_tensor)
806
+ tokenslist.append(plan.total_tokens)
807
+ if debug: print(f"current:{params.sampling_step + 2},selected:{step}")
808
+ # v2 fix: select plans from the SAME step as cond tensors.
809
+ # Previously used a ">= step" comprehension which could collect
810
+ # plans from multiple future steps, making plan/tensor mismatched.
811
+ self._cond_plans = list(regions) # same 'regions' from this break
812
+ break
813
+ self.conds = condslist
814
+ self.contokens = tokenslist
815
+
816
+ uncondslist = []
817
+ untokenslist = []
818
+ unconds = self.hr_unconds_all if self.hrn and self.hr else self.unconds_all
819
+ if unconds is not None:
820
+ for step, regions in unconds[0]:
821
+ if step >= params.sampling_step + 2:
822
+ for plan in regions:
823
+ uncondslist.append(plan.cond_tensor)
824
+ untokenslist.append(plan.total_tokens)
825
+ # v2 fix: same-step synchronisation as cond above.
826
+ self._uncond_plans = list(regions)
827
+ break
828
+ self.unconds = uncondslist
829
+ self.untokens = untokenslist
830
+
831
+ global pn, count
832
+ #pn = False if forge or reforge or classic else True
833
+ pn = True
834
+ count = 0
835
+
836
+ if self.modeltype == "flux" and self.conds:
837
+ # v2 fix:
838
+ # choose the FIRST non-None cond tensor AND remember the MATCHING plan.
839
+ # This keeps appended conditioning and per-span inversion in sync even if
840
+ # region[0] is empty and a later region is the first real NegPiP target.
841
+ for _cond, _plan in zip(self.conds, getattr(self, '_cond_plans', [])):
842
+ if _cond is not None:
843
+ self._flux_cond_plan = _plan
844
+ self.orig_tokens = params.text_cond[COND_KEY_C].shape[1]
845
+ params.text_cond[COND_KEY_C] = torch.cat([params.text_cond[COND_KEY_C], _cond], 1)
846
+ break
847
+
848
+ if self.modeltype == "ZImage" and self.conds:
849
+ # v2 fix:
850
+ # keep the selected appended cond tensor and its plan aligned.
851
+ for _cond, _plan in zip(self.conds, getattr(self, '_cond_plans', [])):
852
+ if _cond is not None:
853
+ self._zimage_cond_plan = _plan
854
+ self.orig_tokens = params.text_cond.shape[1] - 5
855
+ params.text_cond = torch.cat(
856
+ [params.text_cond[:, :-5, :], _cond, params.text_cond[:, -5:, :]],
857
+ 1
858
+ )
859
+ break
860
+
861
+ def _get_negpip_plan(self, is_cond: bool, region_index: int = 0) -> 'NegpipRegionPlan':
862
+ """
863
+ Return the NegpipRegionPlan for the specified cond/uncond branch and region.
864
+
865
+ is_cond=True → cond (positive) branch → self._cond_plans
866
+ is_cond=False → uncond (negative) branch → self._uncond_plans
867
+
868
+ region_index is used for Regional Prompter multi-region routing.
869
+ Falls back to a null plan (no NegPiP effect) rather than crashing if
870
+ the requested index is out of range.
871
+ """
872
+ plans = self._cond_plans if is_cond else self._uncond_plans
873
+ if not plans:
874
+ return NegpipRegionPlan()
875
+ idx = min(region_index, len(plans) - 1)
876
+ return plans[idx]
877
+
878
+
879
+ from pprint import pprint
880
+
881
+ def unload(self,p):
882
+ if hasattr(self,"handle"):
883
+ if forge:
884
+ if self.modeltype == "flux":
885
+ hook_forwards_f(self, p.sd_model.forge_objects.unet.model, remove=True)
886
+ elif self.modeltype == "ZImage":
887
+ hook_forwards_z(self, p.sd_model.forge_objects.unet.model, remove=True)
888
+ else:
889
+ hook_forwards(self, p.sd_model.forge_objects.unet.model, remove=True)
890
+ else:
891
+ hook_forwards(self, p.sd_model.model.diffusion_model, remove=True)
892
+ del self.handle
893
+
894
+ # helper functions from LDM
895
+ def exists(val):
896
+ return val is not None
897
+
898
+ def default(val, d):
899
+ if exists(val):
900
+ return val
901
+ return d() if isfunction(d) else d
902
+
903
+ def hook_forward(self, module):
904
+ def forward(x, context=None, mask=None, value=None, additional_tokens=None, *args, **kwargs):
905
+ if debug: print(" x.shape:",x.shape,"context.shape:",context.shape,"self.contokens",self.contokens,"self.untokens",self.untokens)
906
+
907
+ def sub_forward(x, context, mask, additional_tokens, conds,contokens,unconds,untokens, latent = None):
908
+ if debug: print(" x.shape[0]:",x.shape[0],"batch:",self.batch *2)
909
+
910
+ if x.shape[0] == self.batch *2:
911
+ if debug: print(" x.shape[0] == self.batch *2")
912
+
913
+ if self.rev:
914
+ contn,contp = context.chunk(2)
915
+ ixn,ixp = x.chunk(2)
916
+ else:
917
+ contp,contn = context.chunk(2)
918
+ ixp,ixn = x.chunk(2) #x[0:self.batch,:,:],x[self.batch:,:,:]
919
+
920
+ if conds is not None:
921
+ if contp.shape[0] != conds.shape[0]:
922
+ conds = conds.expand(contp.shape[0],-1,-1)
923
+ contp = torch.cat((contp,conds),1)
924
+ if unconds is not None:
925
+ if contn.shape[0] != unconds.shape[0]:
926
+ unconds = unconds.expand(contn.shape[0],-1,-1)
927
+ contn = torch.cat((contn,unconds),1)
928
+
929
+ # v2: set current plan so main_forward picks the right one
930
+ self._current_negpip_plan = _get_negpip_plan(self, is_cond=True, region_index=0)
931
+ xp = main_forward(self, module, ixp,contp,value,mask,additional_tokens,contokens,args,kwargs)
932
+ self._current_negpip_plan = _get_negpip_plan(self, is_cond=False, region_index=0)
933
+ xn = main_forward(self, module, ixn,contn,value,mask,additional_tokens,untokens,args,kwargs)
934
+ self._current_negpip_plan = None
935
+
936
+ out = torch.cat([xn,xp]) if self.rev else torch.cat([xp,xn])
937
+ return out
938
+
939
+ elif latent is not None:
940
+ if debug:print(" latent is not None")
941
+ if latent:
942
+ conds = conds if conds is not None else None
943
+ else:
944
+ conds = unconds if unconds is not None else None
945
+ if conds is not None:
946
+ if context.shape[0] != conds.shape[0]:
947
+ conds = conds.expand(context.shape[0],-1,-1)
948
+ context = torch.cat([context,conds],1)
949
+
950
+ tokens = contokens if contokens is not None else untokens
951
+
952
+ out = main_forward(self, module, x,context,value,mask,additional_tokens,tokens,args,kwargs)
953
+ return out
954
+
955
+ else:
956
+ if debug:
957
+ print(" Else")
958
+ print(context.shape[1] , self.conlen,self.unlen)
959
+
960
+ tokens = []
961
+ # v2 fix: track branch EXPLICITLY from the context-length test.
962
+ # Do NOT infer cond/uncond by comparing token-list contents —
963
+ # if contokens and untokens happen to be equal, that would misroute.
964
+ _branch_is_cond = False # will be set below when branch is known
965
+ concon = counter(self.isxl)
966
+ if debug: print(concon)
967
+ if context.shape[1] == self.conlen * 77 and concon:
968
+ if conds is not None:
969
+ if context.shape[0] != conds.shape[0]:
970
+ conds = conds.expand(context.shape[0],-1,-1)
971
+ context = torch.cat([context,conds],1)
972
+ tokens = contokens
973
+ _branch_is_cond = True # context length matched cond → positive branch
974
+ elif context.shape[1] == self.unlen * 77 and concon:
975
+ if unconds is not None:
976
+ if context.shape[0] != unconds.shape[0]:
977
+ unconds = unconds.expand(context.shape[0],-1,-1)
978
+ context = torch.cat([context,unconds],1)
979
+ tokens = untokens
980
+ _branch_is_cond = False # context length matched uncond → negative branch
981
+ # v2: set plan using explicitly-determined branch flag, not list comparison
982
+ self._current_negpip_plan = _get_negpip_plan(self, is_cond=_branch_is_cond, region_index=0)
983
+ out = main_forward(self, module, x,context,value,mask,additional_tokens,tokens,args,kwargs)
984
+ self._current_negpip_plan = None
985
+ return out
986
+
987
+ if self.enable_rp_latent:
988
+ if len(self.conds) - 1 >= self.latenti:
989
+ # v2: cond branch uses region-specific plan
990
+ self._current_negpip_plan = _get_negpip_plan(self, is_cond=True, region_index=self.latenti)
991
+ out = sub_forward(x, context, mask, additional_tokens, self.conds[self.latenti],self.contokens[self.latenti],None,None ,latent = True)
992
+ self.latenti += 1
993
+ else:
994
+ # v2: uncond branch uses uncond plan[0]
995
+ self._current_negpip_plan = _get_negpip_plan(self, is_cond=False, region_index=0)
996
+ _unc = self.unconds[0] if (self.unconds and len(self.unconds) > 0) else None
997
+ _utok = self.untokens[0] if (self.untokens and len(self.untokens) > 0) else None
998
+ out = sub_forward(x, context, mask, additional_tokens, None, None, _unc, _utok, latent=False)
999
+ self.latenti = 0
1000
+ self._current_negpip_plan = None
1001
+ return out
1002
+ else:
1003
+ if self.conds is not None and self.unconds is not None and len(self.conds) > 0 and len(self.unconds) > 0:
1004
+ return sub_forward(x, context, mask, additional_tokens, self.conds[0],self.contokens[0],self.unconds[0],self.untokens[0])
1005
+ else:
1006
+ return sub_forward(x, context, mask, additional_tokens, None,None,None,None)
1007
+
1008
+ return forward
1009
+
1010
+ count = 0
1011
+ pn = True
1012
+
1013
+ def counter(isxl):
1014
+ global count, pn
1015
+ count += 1
1016
+
1017
+ limit = 70 if isxl else 16
1018
+ outpn = pn
1019
+
1020
+ if count == limit:
1021
+ pn = not pn
1022
+ count = 0
1023
+ return outpn
1024
+
1025
+ def main_forward2(self, module, x, context, mask, additional_tokens, tokens, args, kwargs):
1026
+ h = module.heads
1027
+ context = context.to(x.dtype)
1028
+ q = module.to_q(x)
1029
+
1030
+ context = default(context, x)
1031
+ k = module.to_k(context)
1032
+ v = module.to_v(context)
1033
+ if debug: print(h,context.shape,q.shape,k.shape,v.shape)
1034
+
1035
+ _, _, dim_head = q.shape
1036
+ dim_head //= h
1037
+ scale = dim_head ** -0.5
1038
+
1039
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
1040
+ sim = einsum('b i d, b j d -> b i j', q, k) * scale
1041
+
1042
+ if self.active:
1043
+ if tokens:
1044
+ for token in tokens:
1045
+ start = (v.shape[1]//77 - len(tokens)) * 77
1046
+ #print("v.shape:",v.shape,"start:",start+1,"stop:",start+token)
1047
+ v[:,start+1:start+token,:] = -v[:,start+1:start+token,:]
1048
+
1049
+ if exists(mask):
1050
+ mask = rearrange(mask, 'b ... -> b (...)')
1051
+ max_neg_value = -torch.finfo(sim.dtype).max
1052
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
1053
+ sim.masked_fill_(~mask, max_neg_value)
1054
+
1055
+ attn = sim.softmax(dim=-1)
1056
+ #print(h,context.shape,q.shape,k.shape,v.shape,attn.shape)
1057
+ out = einsum('b i j, b j d -> b i d', attn, v)
1058
+
1059
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
1060
+
1061
+ return module.to_out(out)
1062
+
1063
+ def main_forward(self, attn, x, context, value = None ,mask = None, temb = None, tokens = [], args = None, kwargs = None):
1064
+ q = attn.to_q(x)
1065
+ context = context.to(x.dtype)
1066
+ context = default(context, x)
1067
+ k = attn.to_k(context)
1068
+ if value is not None:
1069
+ v = attn.to_v(value)
1070
+ del value
1071
+ else:
1072
+ v = attn.to_v(context)
1073
+
1074
+ if self.active:
1075
+ if tokens:
1076
+ if NEGPIP_USE_V2 and hasattr(self, '_current_negpip_plan') and self._current_negpip_plan is not None:
1077
+ # v2: use the plan that sub_forward set for THIS branch/region
1078
+ _apply_negpip_spans(v, self._current_negpip_plan)
1079
+ else:
1080
+ # v1 fallback: uniform inversion of last N tokens
1081
+ v[:, -tokens:, :] = -v[:, -tokens:, :]
1082
+
1083
+ out = attention_function(q, k, v, attn.heads, mask)
1084
+ return attn.to_out(out)
1085
+
1086
+
1087
+ def attention_function(q, k, v, heads, mask=None, attn_precision=None, skip_reshape=False):
1088
+ if skip_reshape:
1089
+ b, _, _, dim_head = q.shape
1090
+ else:
1091
+ b, _, dim_head = q.shape
1092
+ dim_head //= heads
1093
+ q, k, v = map(
1094
+ lambda t: t.view(b, -1, heads, dim_head).transpose(1, 2),
1095
+ (q, k, v),
1096
+ )
1097
+
1098
+ out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
1099
+ out = (
1100
+ out.transpose(1, 2).reshape(b, -1, heads * dim_head)
1101
+ )
1102
+ return out
1103
+
1104
+ def hook_forwards(self, root_module: torch.nn.Module, remove=False):
1105
+ for name, module in root_module.named_modules():
1106
+ if "attn2" in name and module.__class__.__name__ == "CrossAttention":
1107
+ module.forward = hook_forward(self, module)
1108
+ if remove:
1109
+ del module.forward
1110
+
1111
+ def hook_forwards_f(self, root_module: torch.nn.Module, remove=False):
1112
+ for name, module in root_module.named_modules():
1113
+ if "double_blocks" in name and module.__class__.__name__ == "DoubleStreamBlock":
1114
+ module.forward = hook_forward_f_d(self, module)
1115
+ if remove:
1116
+ del module.forward
1117
+
1118
+ if "single_blocks" in name and module.__class__.__name__ == "SingleStreamBlock":
1119
+ module.forward = hook_forward_f_s(self, module)
1120
+ if remove:
1121
+ del module.forward
1122
+
1123
+ def hook_forwards_z(self, root_module: torch.nn.Module, remove=False):
1124
+ for name, module in root_module.named_modules():
1125
+ if "layers" in name and module.__class__.__name__ == "JointAttention":
1126
+ module.forward = hook_forward_f_z(self, module)
1127
+ if remove:
1128
+ del module.forward
1129
+
1130
+ def resetpcache(p):
1131
+ p.cached_c = [None,None]
1132
+ p.cached_uc = [None,None]
1133
+ p.cached_hr_c = [None, None]
1134
+ p.cached_hr_uc = [None, None]
1135
+
1136
+
1137
+ class SdConditioning(list):
1138
+ def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None):
1139
+ super().__init__()
1140
+ self.extend(prompts)
1141
+
1142
+ if copy_from is None:
1143
+ copy_from = prompts
1144
+
1145
+ self.is_negative_prompt = is_negative_prompt or getattr(copy_from, 'is_negative_prompt', False)
1146
+ self.width = width or getattr(copy_from, 'width', None)
1147
+ self.height = height or getattr(copy_from, 'height', None)
1148
+
1149
+ def ext_on_ui_settings():
1150
+ # [setting_name], [default], [label], [component(blank is checkbox)], [component_args]debug_level_choices = []
1151
+ negpip_options = [
1152
+ (OPT_HIDE, False, "Hide in Txt2Img/Img2Img tab(Reload UI required)"),
1153
+ (OPT_ACT, True, "Active(Effective when Hide is Checked)",),
1154
+ ]
1155
+ section = ('negpip', "NegPiP")
1156
+
1157
+ for cur_setting_name, *option_info in negpip_options:
1158
+ shared.opts.add_option(cur_setting_name, shared.OptionInfo(*option_info, section=section))
1159
+
1160
+ on_ui_settings(ext_on_ui_settings)
1161
+
1162
+ def hr_dealer(p):
1163
+ if not hasattr(p, "hr_prompts"):
1164
+ p.hr_prompts = None
1165
+ if not hasattr(p, "hr_negative_prompts"):
1166
+ p.hr_negative_prompts = None
1167
+
1168
+ return bool(p.hr_prompts), bool(p.hr_negative_prompts )
1169
+
1170
+ def hook_forward_f_d(self, module):
1171
+ def double_s_forward(img, txt, vec, pe):
1172
+ img_mod1_shift, img_mod1_scale, img_mod1_gate, img_mod2_shift, img_mod2_scale, img_mod2_gate = module.img_mod(vec)
1173
+
1174
+ img_modulated = module.img_norm1(img)
1175
+ img_modulated = (1 + img_mod1_scale) * img_modulated + img_mod1_shift
1176
+ del img_mod1_shift, img_mod1_scale
1177
+ img_qkv = module.img_attn.qkv(img_modulated)
1178
+ del img_modulated
1179
+
1180
+ # img_q, img_k, img_v = rearrange(img_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
1181
+ B, L, _ = img_qkv.shape
1182
+ H = module.num_heads
1183
+ D = img_qkv.shape[-1] // (3 * H)
1184
+ img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
1185
+ del img_qkv
1186
+
1187
+ img_q, img_k = module.img_attn.norm(img_q, img_k, img_v)
1188
+
1189
+ txt_mod1_shift, txt_mod1_scale, txt_mod1_gate, txt_mod2_shift, txt_mod2_scale, txt_mod2_gate = module.txt_mod(vec)
1190
+ del vec
1191
+
1192
+ txt_modulated = module.txt_norm1(txt)
1193
+
1194
+ txt_modulated = (1 + txt_mod1_scale) * txt_modulated + txt_mod1_shift
1195
+
1196
+ del txt_mod1_shift, txt_mod1_scale
1197
+ txt_qkv = module.txt_attn.qkv(txt_modulated)
1198
+ del txt_modulated
1199
+
1200
+ B, L, _ = txt_qkv.shape
1201
+ txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
1202
+ del txt_qkv
1203
+
1204
+ if NEGPIP_USE_V2:
1205
+ plan = getattr(self, '_flux_cond_plan', None)
1206
+ if plan is not None and plan.total_tokens > 0:
1207
+ # Flux double block processes only the cond stream here.
1208
+ # Use the exact plan that matched the actually appended cond tensor.
1209
+ total = plan.total_tokens
1210
+ for span in plan.spans:
1211
+ cnt, off = span.token_count, span.token_offset
1212
+ end_i = self.orig_tokens + total - off
1213
+ sta_i = end_i - cnt
1214
+ txt_v[:, :, sta_i:end_i, :] = txt_v[:, :, sta_i:end_i, :] * span.sign
1215
+ else:
1216
+ if self.contokens:
1217
+ txt_v[:, :, self.orig_tokens:self.orig_tokens + self.contokens[0], :] = -txt_v[:, :, self.orig_tokens:self.orig_tokens + self.contokens[0], :]
1218
+
1219
+ txt_q, txt_k = module.txt_attn.norm(txt_q, txt_k, txt_v)
1220
+
1221
+ q = torch.cat((txt_q, img_q), dim=2)
1222
+ del txt_q, img_q
1223
+ k = torch.cat((txt_k, img_k), dim=2)
1224
+ del txt_k, img_k
1225
+ v = torch.cat((txt_v, img_v), dim=2)
1226
+ del txt_v, img_v
1227
+
1228
+ attn = attention(q, k, v, pe=pe)
1229
+ del pe, q, k, v
1230
+ txt_attn, img_attn = attn[:, :txt.shape[1]], attn[:, txt.shape[1]:]
1231
+
1232
+ del attn
1233
+
1234
+ img = img + img_mod1_gate * module.img_attn.proj(img_attn)
1235
+ del img_attn, img_mod1_gate
1236
+ img = img + img_mod2_gate * module.img_mlp((1 + img_mod2_scale) * module.img_norm2(img) + img_mod2_shift)
1237
+ del img_mod2_gate, img_mod2_scale, img_mod2_shift
1238
+
1239
+ txt = txt + txt_mod1_gate * module.txt_attn.proj(txt_attn)
1240
+ del txt_attn, txt_mod1_gate
1241
+ txt = txt + txt_mod2_gate * module.txt_mlp((1 + txt_mod2_scale) * module.txt_norm2(txt) + txt_mod2_shift)
1242
+ del txt_mod2_gate, txt_mod2_scale, txt_mod2_shift
1243
+
1244
+ txt = fp16_fix(txt)
1245
+
1246
+ return img, txt
1247
+
1248
+ return double_s_forward
1249
+
1250
+
1251
+ def hook_forward_f_s(self, module):
1252
+ def single_s_forward(x, vec, pe):
1253
+ mod_shift, mod_scale, mod_gate = module.modulation(vec)
1254
+ del vec
1255
+ x_mod = (1 + mod_scale) * module.pre_norm(x) + mod_shift
1256
+ del mod_shift, mod_scale
1257
+ qkv, mlp = torch.split(module.linear1(x_mod), [3 * module.hidden_size, module.mlp_hidden_dim], dim=-1)
1258
+ del x_mod
1259
+
1260
+ # q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
1261
+ qkv = qkv.view(qkv.size(0), qkv.size(1), 3, module.num_heads, module.hidden_size // module.num_heads)
1262
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
1263
+ del qkv
1264
+ if NEGPIP_USE_V2:
1265
+ plan = getattr(self, '_flux_cond_plan', None)
1266
+ if plan is not None and plan.total_tokens > 0:
1267
+ # Flux single block: use the same exact matched plan as append-time.
1268
+ total = plan.total_tokens
1269
+ for span in plan.spans:
1270
+ cnt, off = span.token_count, span.token_offset
1271
+ end_i = self.orig_tokens + total - off
1272
+ sta_i = end_i - cnt
1273
+ v[:, :, sta_i:end_i, :] = v[:, :, sta_i:end_i, :] * span.sign
1274
+ else:
1275
+ if self.contokens:
1276
+ v[:, :, self.orig_tokens:self.orig_tokens + self.contokens[0], :] = -v[:, :, self.orig_tokens:self.orig_tokens + self.contokens[0], :]
1277
+ q, k = module.norm(q, k, v)
1278
+
1279
+ attn = attention(q, k, v, pe=pe)
1280
+ del q, k, v, pe
1281
+ output = module.linear2(torch.cat((attn, module.mlp_act(mlp)), dim=2))
1282
+ del attn, mlp
1283
+
1284
+ x = x + mod_gate * output
1285
+ del mod_gate, output
1286
+
1287
+ x = fp16_fix(x)
1288
+
1289
+ return x
1290
+
1291
+ return single_s_forward
1292
+
1293
+ def hook_forward_f_z(self, module):
1294
+ from backend.nn.lumina import JointAttention
1295
+ from backend.memory_management import xformers_enabled
1296
+ if xformers_enabled():
1297
+ from backend.attention import attention_xformers as attention_function_z
1298
+ else:
1299
+ from backend.attention import attention_pytorch as attention_function_z
1300
+
1301
+ hook_self = self
1302
+
1303
+ def joint_atten_forward(x: torch.Tensor, x_mask: torch.Tensor, freqs_cis: torch.Tensor, transformer_options={}) -> torch.Tensor:
1304
+ bsz, seqlen, _ = x.shape
1305
+
1306
+ xq, xk, xv = torch.split(
1307
+ module.qkv(x),
1308
+ [
1309
+ module.n_local_heads * module.head_dim,
1310
+ module.n_local_kv_heads * module.head_dim,
1311
+ module.n_local_kv_heads * module.head_dim,
1312
+ ],
1313
+ dim=-1,
1314
+ )
1315
+
1316
+ xq = xq.view(bsz, seqlen, module.n_local_heads, module.head_dim)
1317
+ xk = xk.view(bsz, seqlen, module.n_local_kv_heads, module.head_dim)
1318
+ xv = xv.view(bsz, seqlen, module.n_local_kv_heads, module.head_dim)
1319
+
1320
+ if NEGPIP_USE_V2:
1321
+ plan = getattr(hook_self, '_zimage_cond_plan', None)
1322
+ if plan is not None and plan.total_tokens > 0:
1323
+ # v2: ZImage per-span sign application (replaces strength_tensor path)
1324
+ # Use the exact plan that matched the appended cond tensor.
1325
+ # xv shape: (bsz, seqlen, n_heads, head_dim) — span on dim 1
1326
+ total = plan.total_tokens
1327
+ orig = hook_self.orig_tokens
1328
+ for span in plan.spans:
1329
+ cnt, off = span.token_count, span.token_offset
1330
+ end_i = orig + total - off
1331
+ sta_i = end_i - cnt
1332
+ xv[:, sta_i:end_i, :, :] = xv[:, sta_i:end_i, :, :] * span.sign
1333
+ else:
1334
+ if hook_self.contokens and hook_self.conds and hook_self.conds[0] is not None:
1335
+ # v1 fallback: strength_tensor (preserves original ZImage behaviour)
1336
+ start = hook_self.orig_tokens
1337
+ end = start + hook_self.conds[0].shape[1]
1338
+ strength_tensor = torch.tensor(hook_self.strength, device=xv.device, dtype=xv.dtype)
1339
+ strength_tensor = strength_tensor.view(1, -1, 1, 1)
1340
+ xv[:, start:end, :, :] = xv[:, start:end, :, :] * strength_tensor
1341
+
1342
+ xq = module.q_norm(xq)
1343
+ xk = module.k_norm(xk)
1344
+
1345
+ xq = JointAttention.apply_rotary_emb(xq, freqs_cis=freqs_cis)
1346
+ xk = JointAttention.apply_rotary_emb(xk, freqs_cis=freqs_cis)
1347
+
1348
+ n_rep = module.n_local_heads // module.n_local_kv_heads
1349
+ if n_rep >= 1:
1350
+ xk = xk.unsqueeze(3).repeat(1, 1, 1, n_rep, 1).flatten(2, 3)
1351
+ xv = xv.unsqueeze(3).repeat(1, 1, 1, n_rep, 1).flatten(2, 3)
1352
+
1353
+ output = attention_function_z(xq.movedim(1, 2), xk.movedim(1, 2), xv.movedim(1, 2), module.n_local_heads, x_mask, skip_reshape=True, transformer_options=transformer_options)
1354
+
1355
+ return module.out(output)
1356
+
1357
+ return joint_atten_forward
1358
+
1359
+ class InputAccordionImpl(gr.Checkbox):
1360
+ webui_do_not_create_gradio_pyi_thank_you = True
1361
+ global_index = 2244096 + 2 #NegPiP
1362
+
1363
+ @wraps(gr.Checkbox.__init__)
1364
+ def __init__(self, value=None, setup=False, **kwargs):
1365
+ if not setup:
1366
+ super().__init__(value=value, **kwargs)
1367
+ return
1368
+
1369
+ self.accordion_id = kwargs.get('elem_id')
1370
+ if self.accordion_id is None:
1371
+ self.accordion_id = f"input-accordion-m-{InputAccordionImpl.global_index}"
1372
+ InputAccordionImpl.global_index += 1
1373
+
1374
+ kwargs_checkbox = {
1375
+ **kwargs,
1376
+ "elem_id": f"{self.accordion_id}-checkbox",
1377
+ "visible": False,
1378
+ }
1379
+ super().__init__(value=value, **kwargs_checkbox)
1380
+ self.change(fn=None, _js='function(checked){ inputAccordionChecked("' + self.accordion_id + '", checked); }', inputs=[self])
1381
+
1382
+ kwargs_accordion = {
1383
+ **kwargs,
1384
+ "elem_id": self.accordion_id,
1385
+ "label": kwargs.get('label', 'Accordion'),
1386
+ "elem_classes": ['input-accordion-m'],
1387
+ "open": False,
1388
+ }
1389
+
1390
+ self.accordion = gr.Accordion(**kwargs_accordion)
1391
+
1392
+ def extra(self):
1393
+ return gr.Column(elem_id=self.accordion_id + '-extra', elem_classes='input-accordion-extra', min_width=0)
1394
+
1395
+ def __enter__(self):
1396
+ self.accordion.__enter__()
1397
+ return self
1398
+
1399
+ def __exit__(self, exc_type, exc_val, exc_tb):
1400
+ self.accordion.__exit__(exc_type, exc_val, exc_tb)
1401
+
1402
+ def get_block_name(self):
1403
+ return "checkbox"
1404
+
1405
+ def InputAccordion(value=None, **kwargs):
1406
+ return InputAccordionImpl(value=value, setup=True, **kwargs)
1407
+
1408
+ # Check for Gradio version 4; see Forge architecture rework
1409
+ IS_GRADIO_4 = version.parse(gr.__version__) >= version.parse("4.0.0")
1410
+ # check if Forge or auto1111 pure; extremely hacky
1411
+
1412
+ # Forge patches
1413
+
1414
+ # See discussion at, class versus instance __module__
1415
+ # https://github.com/LEv145/--sd-webui-ar-plus/issues/24
1416
+ # Hack for Forge with Gradio 4.0; see `get_component_class_id` in `venv/lib/site-packages/gradio/components/base.py`
1417
+ if IS_GRADIO_4:
1418
+ InputAccordionImpl.__module__ = "modules.ui_components"