├── LICENSE
├── README.md
├── Zho_AlphaChanel.py
├── Zho_ImageComposite.py
├── Zho_RGB_Image.py
├── Zho_TextImage.py
├── Zho_TextImage_frame.py
├── __init__.py
├── font
├── Alkatra.ttf
├── CALIBRI.TTF
├── COMIC.TTF
├── COMICI.TTF
├── COMICZ.TTF
├── Merienda-Black.ttf
├── Merienda-Bold.ttf
├── Merienda-ExtraBold.ttf
├── Merienda-Light.ttf
├── Merienda-Medium.ttf
├── Merienda-Regular.ttf
├── Merienda-SemiBold.ttf
├── Merienda-VariableFont_wght.ttf
└── OverlockSC-Regular.ttf
└── mtb
├── comfy_shared.js
├── debug.js
├── mtb_widgets.js
└── parse-css.js
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ComfyUI-Text_Image-Composite(WIP)
2 | ComfyUI-Text_Image-Composite 说明还在写……
3 |
4 | 
5 |
6 | wrap=0表示自定换行
7 |
8 | 合并了[@h3clikejava](https://github.com/h3clikejava)提交的弧形排版,非常酷!感谢!
9 | 
10 |
11 |
12 | ## 关于我 | About me
13 |
14 | 📬 **联系我**:
15 | - 邮箱:zhozho3965@gmail.com
16 | - QQ 群:839821928
17 |
18 | 🔗 **社交媒体**:
19 | - 个人页:[-Zho-](https://jike.city/zho)
20 | - Bilibili:[我的B站主页](https://space.bilibili.com/484366804)
21 | - X(Twitter):[我的Twitter](https://twitter.com/ZHOZHO672070)
22 | - 小红书:[我的小红书主页](https://www.xiaohongshu.com/user/profile/63f11530000000001001e0c8?xhsshare=CopyLink&appuid=63f11530000000001001e0c8&apptime=1690528872)
23 |
24 | 💡 **支持我**:
25 | - B站:[B站充电](https://space.bilibili.com/484366804)
26 | - 爱发电:[为我充电](https://afdian.net/a/ZHOZHO)
27 |
28 |
29 | ## Credits
30 | - [Allor](https://github.com/Nourepide/ComfyUI-Allor)
31 |
32 | - [MTB](https://github.com/melMass/comfy_mtb)
33 |
--------------------------------------------------------------------------------
/Zho_AlphaChanel.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | class AlphaChanelAddByMask:
4 | def __init__(self):
5 | pass
6 |
7 | @classmethod
8 | def INPUT_TYPES(cls):
9 | return {
10 | "required": {
11 | "images": ("IMAGE",),
12 | "mask": ("MASK",),
13 | "method": (["default", "invert"],),
14 | },
15 | }
16 |
17 | RETURN_TYPES = ("IMAGE",)
18 | FUNCTION = "node"
19 | CATEGORY = "Zho模块组/image"
20 |
21 | def node(self, images, mask, method):
22 | img_height, img_width = images[0, :, :, 0].shape
23 | mask_height, mask_width = mask.shape
24 |
25 | if img_height != mask_height or img_width != mask_width:
26 | raise ValueError(
27 | "[AlphaChanelByMask]: Size of images not equals size of mask. " +
28 | "Images: [" + str(img_width) + ", " + str(img_height) + "] - " +
29 | "Mask: [" + str(mask_width) + ", " + str(mask_height) + "]."
30 | )
31 |
32 | if method == "default":
33 | return (torch.stack([
34 | torch.stack((
35 | images[i, :, :, 0],
36 | images[i, :, :, 1],
37 | images[i, :, :, 2],
38 | 1. - mask
39 | ), dim=-1) for i in range(len(images))
40 | ]),)
41 | else:
42 | return (torch.stack([
43 | torch.stack((
44 | images[i, :, :, 0],
45 | images[i, :, :, 1],
46 | images[i, :, :, 2],
47 | mask
48 | ), dim=-1) for i in range(len(images))
49 | ]),)
50 |
51 |
52 | NODE_CLASS_MAPPINGS = {
53 | "AlphaChanelAddByMask": AlphaChanelAddByMask,
54 | }
55 |
--------------------------------------------------------------------------------
/Zho_ImageComposite.py:
--------------------------------------------------------------------------------
1 | import torchvision.transforms as t
2 | import torch
3 | from PIL import Image as ImageF
4 | from PIL.Image import Image as ImageB
5 | from torch import Tensor, dtype
6 |
7 | def tensor_to_image(self):
8 | return t.ToPILImage()(self.permute(2, 0, 1))
9 |
10 | def image_to_tensor(self):
11 | return t.ToTensor()(self).permute(1, 2, 0)
12 |
13 | Tensor.tensor_to_image = tensor_to_image
14 | ImageB.image_to_tensor = image_to_tensor
15 |
16 | #--------------------------------------------------------
17 | class ImageComposite_Zho:
18 | def __init__(self):
19 | pass
20 |
21 | @classmethod
22 | def INPUT_TYPES(cls):
23 | return {
24 | "required": {
25 | "images_a": ("IMAGE",),
26 | "images_b": ("IMAGE",),
27 | "alpha_a": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像a透明度的参数
28 | "alpha_b": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像b透明度的参数
29 | "images_a_x": ("INT", {
30 | "default": 0,
31 | "step": 1
32 | }),
33 | "images_a_y": ("INT", {
34 | "default": 0,
35 | "step": 1
36 | }),
37 | "images_b_x": ("INT", {
38 | "default": 0,
39 | "step": 1
40 | }),
41 | "images_b_y": ("INT", {
42 | "default": 0,
43 | "step": 1
44 | }),
45 | "container_width": ("INT", {
46 | "default": 0,
47 | "step": 1
48 | }),
49 | "container_height": ("INT", {
50 | "default": 0,
51 | "step": 1
52 | }),
53 | "background": (["images_a", "images_b"],),
54 | "method": (["pair", "matrix"],),
55 | },
56 | }
57 |
58 | RETURN_TYPES = ("IMAGE",)
59 | FUNCTION = "node"
60 | CATEGORY = "Zho模块组/image"
61 |
62 | def node(
63 | self,
64 | images_a,
65 | images_b,
66 | images_a_x,
67 | images_a_y,
68 | images_b_x,
69 | images_b_y,
70 | container_width,
71 | container_height,
72 | background,
73 | method,
74 | alpha_a=1.0,
75 | alpha_b=1.0,
76 | ):
77 | def clip(value: float):
78 | return value if value >= 0 else 0
79 |
80 | # noinspection PyUnresolvedReferences
81 | def composite(image_a, image_b):
82 | img_a_height, img_a_width, img_a_dim = image_a.shape
83 | img_b_height, img_b_width, img_b_dim = image_b.shape
84 |
85 | if img_a_dim == 3:
86 | image_a = torch.stack([
87 | image_a[:, :, 0],
88 | image_a[:, :, 1],
89 | image_a[:, :, 2],
90 | torch.ones((img_a_height, img_a_width)) * alpha_a
91 | ], dim=2)
92 |
93 | if img_b_dim == 3:
94 | image_b = torch.stack([
95 | image_b[:, :, 0],
96 | image_b[:, :, 1],
97 | image_b[:, :, 2],
98 | torch.ones((img_b_height, img_b_width)) * alpha_b
99 | ], dim=2)
100 |
101 | container_x = max(img_a_width, img_b_width) if container_width == 0 else container_width
102 | container_y = max(img_a_height, img_b_height) if container_height == 0 else container_height
103 |
104 | container_a = torch.zeros((container_y, container_x, 4))
105 | container_b = torch.zeros((container_y, container_x, 4))
106 |
107 | img_a_height_c, img_a_width_c = [
108 | clip((images_a_y + img_a_height) - container_y),
109 | clip((images_a_x + img_a_width) - container_x)
110 | ]
111 |
112 | img_b_height_c, img_b_width_c = [
113 | clip((images_b_y + img_b_height) - container_y),
114 | clip((images_b_x + img_b_width) - container_x)
115 | ]
116 |
117 | if img_a_height_c <= img_a_height and img_a_width_c <= img_a_width:
118 | container_a[
119 | images_a_y:img_a_height + images_a_y - img_a_height_c,
120 | images_a_x:img_a_width + images_a_x - img_a_width_c
121 | ] = image_a[
122 | :img_a_height - img_a_height_c,
123 | :img_a_width - img_a_width_c
124 | ]
125 |
126 | if img_b_height_c <= img_b_height and img_b_width_c <= img_b_width:
127 | container_b[
128 | images_b_y:img_b_height + images_b_y - img_b_height_c,
129 | images_b_x:img_b_width + images_b_x - img_b_width_c
130 | ] = image_b[
131 | :img_b_height - img_b_height_c,
132 | :img_b_width - img_b_width_c
133 | ]
134 |
135 | if background == "images_a":
136 | return ImageF.alpha_composite(
137 | container_a.tensor_to_image(),
138 | container_b.tensor_to_image()
139 | ).image_to_tensor()
140 | else:
141 | return ImageF.alpha_composite(
142 | container_b.tensor_to_image(),
143 | container_a.tensor_to_image()
144 | ).image_to_tensor()
145 |
146 | if method == "pair":
147 | if len(images_a) != len(images_b):
148 | raise ValueError("Size of image_a and image_b not equals for pair batch type.")
149 |
150 | return (torch.stack([
151 | composite(images_a[i], images_b[i]) for i in range(len(images_a))
152 | ]),)
153 | elif method == "matrix":
154 | return (torch.stack([
155 | composite(images_a[i], images_b[j]) for i in range(len(images_a)) for j in range(len(images_b))
156 | ]),)
157 |
158 | return None
159 |
160 | #--------------------------------------------------------
161 | class ImageComposite_BG_Zho:
162 | def __init__(self):
163 | pass
164 |
165 | @classmethod
166 | def INPUT_TYPES(cls):
167 | return {
168 | "required": {
169 | "container": ("IMAGE",),
170 | "images_a": ("IMAGE",),
171 | "images_b": ("IMAGE",),
172 | "alpha_a": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像a透明度的参数
173 | "alpha_b": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像b透明度的参数
174 | "images_a_x": ("INT", {
175 | "default": 0,
176 | "step": 1
177 | }),
178 | "images_a_y": ("INT", {
179 | "default": 0,
180 | "step": 1
181 | }),
182 | "images_b_x": ("INT", {
183 | "default": 0,
184 | "step": 1
185 | }),
186 | "images_b_y": ("INT", {
187 | "default": 0,
188 | "step": 1
189 | }),
190 | "background": (["images_a", "images_b"],),
191 | "method": (["pair", "matrix"],),
192 | },
193 | }
194 |
195 | RETURN_TYPES = ("IMAGE",)
196 | FUNCTION = "node"
197 | CATEGORY = "Zho模块组/image"
198 |
199 | def node(
200 | self,
201 | container,
202 | images_a,
203 | images_b,
204 | images_a_x,
205 | images_a_y,
206 | images_b_x,
207 | images_b_y,
208 | background,
209 | method,
210 | alpha_a=1.0,
211 | alpha_b=1.0,
212 | ):
213 | return ImageComposite_Zho().node(
214 | images_a,
215 | images_b,
216 | images_a_x,
217 | images_a_y,
218 | images_b_x,
219 | images_b_y,
220 | container[0, :, :, 0].shape[1],
221 | container[0, :, :, 0].shape[0],
222 | background,
223 | method,
224 | alpha_a=alpha_a,
225 | alpha_b=alpha_b,
226 | )
227 |
228 | #--------------------------------------------------------
229 | class ImageCompositeBy_Zho:
230 | def __init__(self):
231 | pass
232 |
233 | @classmethod
234 | def INPUT_TYPES(cls):
235 | return {
236 | "required": {
237 | "images_a": ("IMAGE",),
238 | "images_b": ("IMAGE",),
239 | "alpha_a": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像a透明度的参数
240 | "alpha_b": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像b透明度的参数
241 | "images_a_x": ("FLOAT", {
242 | "default": 0.0,
243 | "max": 1.0,
244 | "step": 0.01
245 | }),
246 | "images_a_y": ("FLOAT", {
247 | "default": 0.0,
248 | "max": 1.0,
249 | "step": 0.01
250 | }),
251 | "images_b_x": ("FLOAT", {
252 | "default": 0.0,
253 | "max": 1.0,
254 | "step": 0.01
255 | }),
256 | "images_b_y": ("FLOAT", {
257 | "default": 0.0,
258 | "max": 1.0,
259 | "step": 0.01
260 | }),
261 | "background": (["images_a", "images_b"],),
262 | "container_size_type": (["max", "sum", "sum_width", "sum_height"],),
263 | "method": (["pair", "matrix"],),
264 | },
265 | }
266 |
267 | RETURN_TYPES = ("IMAGE",)
268 | FUNCTION = "node"
269 | CATEGORY = "Zho模块组/image"
270 |
271 | def node(
272 | self,
273 | images_a,
274 | images_b,
275 | images_a_x,
276 | images_a_y,
277 | images_b_x,
278 | images_b_y,
279 | background,
280 | container_size_type,
281 | method,
282 | alpha_a=1.0,
283 | alpha_b=1.0,
284 | ):
285 | def offset_by_percent(container_size: int, image_size: int, percent: float):
286 | return int((container_size - image_size) * percent)
287 |
288 | img_a_height, img_a_width = images_a[0, :, :, 0].shape
289 | img_b_height, img_b_width = images_b[0, :, :, 0].shape
290 |
291 | if container_size_type == "max":
292 | container_width = max(img_a_width, img_b_width)
293 | container_height = max(img_a_height, img_b_height)
294 | elif container_size_type == "sum":
295 | container_width = img_a_width + img_b_width
296 | container_height = img_a_height + img_b_height
297 | elif container_size_type == "sum_width":
298 | if img_a_height != img_b_height:
299 | raise ValueError()
300 |
301 | container_width = img_a_width + img_b_width
302 | container_height = img_a_height
303 | elif container_size_type == "sum_height":
304 | if img_b_width != img_b_width:
305 | raise ValueError()
306 |
307 | container_width = img_a_width
308 | container_height = img_a_height + img_a_height
309 | else:
310 | raise ValueError()
311 |
312 | return ImageComposite_Zho().node(
313 | images_a,
314 | images_b,
315 | offset_by_percent(container_width, img_a_width, images_a_x),
316 | offset_by_percent(container_height, img_a_height, images_a_y),
317 | offset_by_percent(container_width, img_b_width, images_b_x),
318 | offset_by_percent(container_height, img_b_height, images_b_y),
319 | container_width,
320 | container_height,
321 | background,
322 | method,
323 | alpha_a=alpha_a,
324 | alpha_b=alpha_b
325 | )
326 |
327 | #--------------------------------------------------------
328 | class ImageCompositeBy_BG_Zho:
329 | def __init__(self):
330 | pass
331 |
332 | @classmethod
333 | def INPUT_TYPES(cls):
334 | return {
335 | "required": {
336 | "container": ("IMAGE",),
337 | "images_a": ("IMAGE",),
338 | "images_b": ("IMAGE",),
339 | "alpha_a": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像a透明度的参数
340 | "alpha_b": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), # 添加控制图像b透明度的参数
341 | "images_a_x": ("FLOAT", {
342 | "default": 0.0,
343 | "max": 1.0,
344 | "step": 0.01
345 | }),
346 | "images_a_y": ("FLOAT", {
347 | "default": 0.0,
348 | "max": 1.0,
349 | "step": 0.01
350 | }),
351 | "images_b_x": ("FLOAT", {
352 | "default": 0.0,
353 | "max": 1.0,
354 | "step": 0.01
355 | }),
356 | "images_b_y": ("FLOAT", {
357 | "default": 0.0,
358 | "max": 1.0,
359 | "step": 0.01
360 | }),
361 | "background": (["images_a", "images_b"],),
362 | "method": (["pair", "matrix"],),
363 | },
364 | }
365 |
366 | RETURN_TYPES = ("IMAGE",)
367 | FUNCTION = "node"
368 | CATEGORY = "Zho模块组/image"
369 |
370 | def node(
371 | self,
372 | container,
373 | images_a,
374 | images_b,
375 | images_a_x,
376 | images_a_y,
377 | images_b_x,
378 | images_b_y,
379 | background,
380 | method,
381 | alpha_a=1.0,
382 | alpha_b=1.0,
383 | ):
384 | def offset_by_percent(container_size: int, image_size: int, percent: float):
385 | return int((container_size - image_size) * percent)
386 |
387 | img_a_height, img_a_width = images_a[0, :, :, 0].shape
388 | img_b_height, img_b_width = images_b[0, :, :, 0].shape
389 |
390 | container_width = container[0, :, :, 0].shape[1]
391 | container_height = container[0, :, :, 0].shape[0]
392 |
393 | if container_width < max(img_a_width, img_b_width) or container_height < max(img_a_height, img_b_height):
394 | raise ValueError("Container can't be smaller then max width or height of images.")
395 |
396 | return ImageComposite_Zho().node(
397 | images_a,
398 | images_b,
399 | offset_by_percent(container_width, img_a_width, images_a_x),
400 | offset_by_percent(container_height, img_a_height, images_a_y),
401 | offset_by_percent(container_width, img_b_width, images_b_x),
402 | offset_by_percent(container_height, img_b_height, images_b_y),
403 | container_width,
404 | container_height,
405 | background,
406 | method,
407 | alpha_a=alpha_a,
408 | alpha_b=alpha_b
409 | )
410 |
411 |
412 | NODE_CLASS_MAPPINGS = {
413 | "ImageComposite_Zho": ImageComposite_Zho,
414 | "ImageComposite_BG_Zho": ImageComposite_BG_Zho,
415 | "ImageCompositeBy_Zho": ImageCompositeBy_Zho,
416 | "ImageCompositeBy_BG_Zho": ImageCompositeBy_BG_Zho
417 | }
418 |
--------------------------------------------------------------------------------
/Zho_RGB_Image.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from PIL import Image
3 | from typing import List, Optional, Union
4 | import numpy as np
5 |
6 | def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
7 | if isinstance(image, list):
8 | return torch.cat([pil2tensor(img) for img in image], dim=0)
9 |
10 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
11 |
12 | # 添加一个辅助函数,用于交换宽度和高度
13 | def swap_width_height(width, height):
14 | return height, width
15 |
16 | class RGB_Image_Zho:
17 | def __init__(self) -> None:
18 | pass
19 |
20 | @classmethod
21 | def INPUT_TYPES(cls):
22 | return {
23 | "required": {
24 | "width": ("INT", {"default": 512, "min": 16, "max": 8160}),
25 | "height": ("INT", {"default": 512, "min": 16, "max": 8160}),
26 | "swap": ("BOOLEAN", {"default": False}), # 添加交换宽度和高度的按钮
27 | "color": ("COLOR",),
28 | }
29 | }
30 |
31 | RETURN_TYPES = ("IMAGE",)
32 | FUNCTION = "rgb_image"
33 | CATEGORY = "Zho模块组/image"
34 |
35 | def rgb_image(self, color, width, height, swap=False):
36 | # 如果用户选择交换宽度和高度,则调用交换函数
37 | if swap:
38 | width, height = swap_width_height(width, height)
39 |
40 | # 创建RGBA图像
41 | image = Image.new("RGB", (width, height), color=color)
42 |
43 | # 转换为张量
44 | image = pil2tensor(image)
45 |
46 | return (image,)
47 |
48 |
49 | #----------------------------------------------------------------------------
50 | NODE_CLASS_MAPPINGS = {
51 | "RGB_Image_Zho": RGB_Image_Zho,
52 | }
--------------------------------------------------------------------------------
/Zho_TextImage.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 | from typing import cast
3 | from typing import List, Optional, Union
4 | import numpy as np
5 | import torch
6 | from PIL import Image, ImageDraw, ImageFont
7 | import math
8 |
9 | #----------------------------------------------------------------------------
10 | here = Path(__file__).parent.absolute()
11 | comfy_dir = here.parent.parent
12 |
13 | #----------------------------------------------------------------------------
14 | def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
15 | if isinstance(image, list):
16 | return torch.cat([pil2tensor(img) for img in image], dim=0)
17 |
18 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
19 |
20 | #----------------------------------------------------------------------------
21 | # 添加一个辅助函数,用于交换宽度和高度
22 | def swap_width_height(width, height):
23 | return height, width
24 |
25 | #----------------------------------------------------------------------------
26 | import logging
27 | import re
28 | import os
29 |
30 | base_log_level = logging.DEBUG if os.environ.get("MTB_DEBUG") else logging.INFO
31 |
32 |
33 | # Custom object that discards the output
34 | class NullWriter:
35 | def write(self, text):
36 | pass
37 |
38 |
39 | class Formatter(logging.Formatter):
40 | grey = "\x1b[38;20m"
41 | cyan = "\x1b[36;20m"
42 | purple = "\x1b[35;20m"
43 | yellow = "\x1b[33;20m"
44 | red = "\x1b[31;20m"
45 | bold_red = "\x1b[31;1m"
46 | reset = "\x1b[0m"
47 | # format = "%(asctime)s - [%(name)s] - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
48 | format = "[%(name)s] | %(levelname)s -> %(message)s"
49 |
50 | FORMATS = {
51 | logging.DEBUG: purple + format + reset,
52 | logging.INFO: cyan + format + reset,
53 | logging.WARNING: yellow + format + reset,
54 | logging.ERROR: red + format + reset,
55 | logging.CRITICAL: bold_red + format + reset,
56 | }
57 |
58 | def format(self, record):
59 | log_fmt = self.FORMATS.get(record.levelno)
60 | formatter = logging.Formatter(log_fmt)
61 | return formatter.format(record)
62 |
63 |
64 | def mklog(name, level=base_log_level):
65 | logger = logging.getLogger(name)
66 | logger.setLevel(level)
67 |
68 | for handler in logger.handlers:
69 | logger.removeHandler(handler)
70 |
71 | ch = logging.StreamHandler()
72 | ch.setLevel(level)
73 | ch.setFormatter(Formatter())
74 | logger.addHandler(ch)
75 |
76 | # Disable log propagation
77 | logger.propagate = False
78 |
79 | return logger
80 |
81 |
82 | # - The main app logger
83 | log = mklog(__package__, base_log_level)
84 |
85 |
86 | def log_user(arg):
87 | print("\033[34mComfy MTB Utils:\033[0m {arg}")
88 |
89 |
90 | def get_summary(docstring):
91 | return docstring.strip().split("\n\n", 1)[0]
92 |
93 |
94 | def blue_text(text):
95 | return f"\033[94m{text}\033[0m"
96 |
97 |
98 | def cyan_text(text):
99 | return f"\033[96m{text}\033[0m"
100 |
101 |
102 | def get_label(label):
103 | words = re.findall(r"(?:^|[A-Z])[a-z]*", label)
104 | return " ".join(words).strip()
105 |
106 | # 禁用 aiohttp 的访问日志记录器
107 | logging.getLogger('aiohttp.access').disabled = True
108 | #----------------------------------------------------------------------------
109 | def bbox_dim(bbox):
110 | left, upper, right, lower = bbox
111 | width = right - left
112 | height = lower - upper
113 | return width, height
114 |
115 | #----------------------------------------------------------------------------
116 | class Text_Image_Zho:
117 |
118 | fonts = {}
119 |
120 | def __init__(self):
121 | # - This is executed when the graph is executed, we could conditionaly reload fonts there
122 | pass
123 |
124 | @classmethod
125 | def CACHE_FONTS(cls):
126 | font_extensions = ["*.ttf", "*.otf", "*.woff", "*.woff2", "*.eot"]
127 | fonts = []
128 |
129 | for extension in font_extensions:
130 | fonts.extend(comfy_dir.glob(f"**/{extension}"))
131 |
132 | if not fonts:
133 | log.warn(
134 | "> No fonts found in the comfy folder, place at least one font file somewhere in ComfyUI's hierarchy"
135 | )
136 | else:
137 | log.debug(f"> Found {len(fonts)} fonts")
138 |
139 | for font in fonts:
140 | log.debug(f"Adding font {font}")
141 | cls.fonts[font.stem] = font.as_posix()
142 |
143 | @classmethod
144 | def INPUT_TYPES(cls):
145 | if not cls.fonts:
146 | cls.CACHE_FONTS()
147 | else:
148 | log.debug(f"Using cached fonts (count: {len(cls.fonts)})")
149 | return {
150 | "required": {
151 | "text": (
152 | "STRING",
153 | {"default": "ZHOZHOZHO"},
154 | ),
155 | "selected_font": ((sorted(cls.fonts.keys())),),
156 | "align": (["left", "center", "right"],
157 | ),
158 | "wrap": (
159 | "INT",
160 | {"default": 0, "min": 0, "max": 8096, "step": 1},
161 | ),
162 | "font_size": (
163 | "INT",
164 | {"default": 12, "min": 1, "max": 2500, "step": 1},
165 | ),
166 | "color": (
167 | "COLOR",
168 | {"default": "red"},
169 | ),
170 | "outline_size": (
171 | "INT",
172 | {"default": 0, "min": 0, "max": 8096, "step": 1},
173 | ),
174 | "outline_color": (
175 | "COLOR",
176 | {"default": "blue"}, # 设置默认的描边颜色
177 | ),
178 | "margin_x": (
179 | "INT",
180 | {"default": 0, "min": 0, "max": 8096, "step": 1},
181 | ),
182 | "margin_y": (
183 | "INT",
184 | {"default": 0, "min": 0, "max": 8096, "step": 1},
185 | ),
186 | "width": (
187 | "INT",
188 | {"default": 512, "min": 1, "max": 8096, "step": 1},
189 | ),
190 | "height": (
191 | "INT",
192 | {"default": 512, "min": 1, "max": 8096, "step": 1},
193 | ),
194 | "swap": ("BOOLEAN", {"default": False}), # 添加交换宽度和高度的按钮
195 | "arc_text": ("BOOLEAN", {"default": False}),
196 | "arc_radius": (
197 | "INT",
198 | {"default": 100, "min": 1, "max": 2500, "step": 1},
199 | ),
200 | "arc_start_angle": (
201 | "INT",
202 | {"default": 180, "min": 0, "max": 360, "step": 1},
203 | ),
204 | "arc_end_angle": (
205 | "INT",
206 | {"default": 360, "min": 0, "max": 360, "step": 1},
207 | ),
208 | }
209 | }
210 |
211 | RETURN_TYPES = ("IMAGE",)
212 | RETURN_NAMES = ("image",)
213 | FUNCTION = "text_to_image"
214 | CATEGORY = "Zho模块组/text"
215 |
216 | def draw_text_in_arc(self, image, draw, text, font, font_path, font_size, center, radius, start_angle, end_angle, fill='black', stroke_fill='blue', stroke_width=0):
217 | # 文字的总长度
218 | text_width = sum(font.getsize(char)[0] for char in text[:-1])
219 |
220 | # 根据扇形角度计算角度步长
221 | angle_range = end_angle - start_angle
222 | angle_step = (angle_range / (len(text) - 1) if len(text) > 1 else 1)
223 |
224 | # 开始绘制文字
225 | current_angle = start_angle
226 | for char in text:
227 | char_width, char_height = font.getsize(char)
228 | angle = math.radians(current_angle)
229 | print(current_angle, angle, angle_step)
230 |
231 | # 创建单独的图像用于旋转字符
232 | super_sampling_multiplier = 10
233 | char_image = Image.new("RGBA", (char_width * super_sampling_multiplier, char_height * super_sampling_multiplier), (0, 0, 0, 0))
234 | char_draw = ImageDraw.Draw(char_image)
235 | super_sampling_font = cast(ImageFont.FreeTypeFont, ImageFont.truetype(font_path, font_size * super_sampling_multiplier))
236 | char_draw.text((0, 0), char, font=super_sampling_font, fill=fill, stroke_fill=stroke_fill, stroke_width=stroke_width)
237 |
238 | # 计算旋转角度和字符位置
239 | rotate_angle = current_angle - 90 - (current_angle - 180) * 2 # 使字符面向圆心
240 | rotated_char_image = char_image.rotate(rotate_angle, expand=1, resample=Image.BICUBIC)
241 | # 缩小图像大小
242 | new_size = (int(rotated_char_image.width / 10), int(rotated_char_image.height / 10))
243 | rotated_char_image_resized = rotated_char_image.resize(new_size, Image.ANTIALIAS)
244 |
245 | # 计算缩小后的图像放置位置
246 | x = center[0] + radius * math.cos(angle) - rotated_char_image_resized.size[0] / 2
247 | y = center[1] + radius * math.sin(angle) - rotated_char_image_resized.size[1] / 2
248 |
249 | # 粘贴缩小后的图像
250 | image.paste(rotated_char_image_resized, (int(x), int(y)), rotated_char_image_resized)
251 |
252 | # 更新下一个字符的开始角度
253 | current_angle += angle_step
254 |
255 |
256 | def text_to_image(
257 | self, text, selected_font, align, wrap, font_size, width, height, color, outline_size, outline_color, margin_x, margin_y, swap=False, arc_text=False, arc_radius=100, arc_start_angle=180, arc_end_angle=360
258 | ):
259 | import textwrap
260 |
261 | # 如果用户选择交换宽度和高度,则调用交换函数
262 | if swap:
263 | width, height = swap_width_height(width, height)
264 |
265 | font_path = self.fonts[selected_font]
266 | (_, top, _, _) = ImageFont.truetype(font_path, font_size).getbbox(text)
267 | font = cast(ImageFont.FreeTypeFont, ImageFont.truetype(font_path, font_size))
268 | if wrap == 0:
269 | wrap = width / font_size
270 | wrap = int(wrap)
271 | lines = textwrap.wrap(text, width=wrap)
272 | log.debug(f"Lines: {lines}")
273 | line_height = bbox_dim(font.getbbox("hg"))[1]
274 | img_height = height # line_height * len(lines)
275 | img_width = width # max(font.getsize(line)[0] for line in lines)
276 |
277 | img = Image.new("RGBA", (img_width, img_height), (0, 0, 0, 0))
278 | draw = ImageDraw.Draw(img)
279 |
280 | # 曲线文字
281 | if arc_text:
282 | width, height = bbox_dim(font.getbbox(text))
283 |
284 | center_x = (img_width) // 2
285 | center_y = arc_radius + (height)
286 |
287 | if align == "left":
288 | center_x = arc_radius + (height) // 2
289 | elif align == "right":
290 | center_x = img_width - arc_radius - (height) // 2
291 | center = (center_x + margin_x, center_y + margin_y)
292 | self.draw_text_in_arc(img, draw, text, font, font_path, font_size, center, arc_radius, arc_start_angle, arc_end_angle,
293 | fill=color, stroke_fill=outline_color, stroke_width=outline_size)
294 | else:
295 | # 初始化 y_text
296 | y_text = margin_y + outline_size - top
297 |
298 | for line in lines:
299 | width, height = bbox_dim(font.getbbox(line))
300 |
301 | # 根据 align 参数计算文本的 x 坐标
302 | if align == "left":
303 | x_text = margin_x
304 | elif align == "center":
305 | x_text = (img_width - width) // 2
306 | elif align == "right":
307 | x_text = img_width - width - margin_x
308 | else:
309 | x_text = margin_x # 默认为左对齐
310 |
311 | draw.text(
312 | (x_text, y_text),
313 | text=line,
314 | fill=color,
315 | stroke_fill=outline_color,
316 | stroke_width=outline_size,
317 | font=font,
318 | )
319 | y_text += height
320 |
321 | return (pil2tensor(img),)
322 |
323 | #----------------------------------------------------------------------------
324 | class Text_Image_Multiline_Zho:
325 |
326 | fonts = {}
327 |
328 | def __init__(self):
329 | # - This is executed when the graph is executed, we could conditionaly reload fonts there
330 | pass
331 |
332 | @classmethod
333 | def CACHE_FONTS(cls):
334 | font_extensions = ["*.ttf", "*.otf", "*.woff", "*.woff2", "*.eot"]
335 | fonts = []
336 |
337 | for extension in font_extensions:
338 | fonts.extend(comfy_dir.glob(f"**/{extension}"))
339 |
340 | if not fonts:
341 | log.warn(
342 | "> No fonts found in the comfy folder, place at least one font file somewhere in ComfyUI's hierarchy"
343 | )
344 | else:
345 | log.debug(f"> Found {len(fonts)} fonts")
346 |
347 | for font in fonts:
348 | log.debug(f"Adding font {font}")
349 | cls.fonts[font.stem] = font.as_posix()
350 |
351 | @classmethod
352 | def INPUT_TYPES(cls):
353 | if not cls.fonts:
354 | cls.CACHE_FONTS()
355 | else:
356 | log.debug(f"Using cached fonts (count: {len(cls.fonts)})")
357 | return {
358 | "required": {
359 | "text": (
360 | "STRING",
361 | {"default": "ZHOZHOZHO", "multiline": True},
362 | ),
363 | "selected_font": ((sorted(cls.fonts.keys())),),
364 | "align": (["left", "center", "right"],
365 | ),
366 | "wrap": (
367 | "INT",
368 | {"default": 120, "min": 0, "max": 8096, "step": 1},
369 | ),
370 | "graphspace": (
371 | "INT",
372 | {"default": 10, "min": 0, "max": 8096, "step": 1},
373 | ),
374 | "linespace": (
375 | "INT",
376 | {"default": 2, "min": 0, "max": 8096, "step": 1},
377 | ),
378 | "font_size": (
379 | "INT",
380 | {"default": 12, "min": 1, "max": 2500, "step": 1},
381 | ),
382 | "color": (
383 | "COLOR",
384 | {"default": "red"},
385 | ),
386 | "outline_size": (
387 | "INT",
388 | {"default": 0, "min": 0, "max": 8096, "step": 1},
389 | ),
390 | "outline_color": (
391 | "COLOR",
392 | {"default": "blue"}, # 设置默认的描边颜色
393 | ),
394 | "margin_x": (
395 | "INT",
396 | {"default": 0, "min": 0, "max": 8096, "step": 1},
397 | ),
398 | "margin_y": (
399 | "INT",
400 | {"default": 0, "min": 0, "max": 8096, "step": 1},
401 | ),
402 | "width": (
403 | "INT",
404 | {"default": 512, "min": 1, "max": 8096, "step": 1},
405 | ),
406 | "height": (
407 | "INT",
408 | {"default": 512, "min": 1, "max": 8096, "step": 1},
409 | ),
410 | "swap": ("BOOLEAN", {"default": False}), # 添加交换宽度和高度的按钮
411 | }
412 | }
413 |
414 | RETURN_TYPES = ("IMAGE",)
415 | RETURN_NAMES = ("image",)
416 | FUNCTION = "text_to_image_multiline"
417 | CATEGORY = "Zho模块组/text"
418 |
419 | def text_to_image_multiline(
420 | self, text, selected_font, align, wrap, graphspace, linespace, font_size, width, height, color, outline_size, outline_color, margin_x, margin_y, swap=False
421 | ):
422 | from PIL import Image, ImageDraw, ImageFont
423 | import textwrap
424 |
425 | # 如果用户选择交换宽度和高度,则调用交换函数
426 | if swap:
427 | width, height = swap_width_height(width, height)
428 |
429 | font_path = self.fonts[selected_font]
430 | (_, top, _, _) = ImageFont.truetype(font_path, font_size).getbbox(text)
431 | font = cast(ImageFont.FreeTypeFont, ImageFont.truetype(font_path, font_size))
432 | if wrap == 0:
433 | wrap = width / font_size
434 | wrap = int(wrap)
435 |
436 | paragraphs = text.split('\n')
437 |
438 | log.debug(f"Paragraphs: {paragraphs}")
439 |
440 | img_height = height # line_height * len(lines)
441 | img_width = width # max(font.getsize(line)[0] for line in lines)
442 |
443 | img = Image.new("RGBA", (img_width, img_height), (0, 0, 0, 0))
444 | draw = ImageDraw.Draw(img)
445 |
446 | # 初始化 y_text
447 | y_text = margin_y + outline_size
448 |
449 | for paragraph in paragraphs:
450 | lines = textwrap.wrap(paragraph, width=wrap, expand_tabs=False, replace_whitespace=False)
451 |
452 | for line in lines:
453 | width, height = bbox_dim(font.getbbox(line))
454 |
455 | # 根据 align 参数重新计算 x 坐标
456 | if align == "left":
457 | x_text = margin_x
458 | elif align == "center":
459 | x_text = (img_width - width) // 2
460 | elif align == "right":
461 | x_text = img_width - width - margin_x
462 | else:
463 | x_text = margin_x # 默认为左对齐
464 |
465 | draw.text(
466 | (x_text, y_text),
467 | text=line,
468 | fill=color,
469 | stroke_fill=outline_color,
470 | stroke_width=outline_size,
471 | font=font,
472 | )
473 |
474 | # 更新 y 坐标,加上当前行的高度和一些额外的间距
475 | y_text += height + linespace # linespace 是行之间的额外间距
476 |
477 | # 段落之间添加一些额外的间距
478 | y_text += graphspace # 可以根据需要调整
479 |
480 | return (pil2tensor(img),)
481 |
482 |
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 | #----------------------------------------------------------------------------
491 | NODE_CLASS_MAPPINGS = {
492 | "Text_Image_Zho": Text_Image_Zho,
493 | "Text_Image_Multiline_Zho": Text_Image_Multiline_Zho,
494 | }
--------------------------------------------------------------------------------
/Zho_TextImage_frame.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 | from typing import cast
3 | from typing import List, Optional, Union
4 | import numpy as np
5 | import torch
6 | from PIL import Image
7 |
8 | #----------------------------------------------------------------------------
9 | here = Path(__file__).parent.absolute()
10 | comfy_dir = here.parent.parent
11 |
12 | #----------------------------------------------------------------------------
13 | def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
14 | if isinstance(image, list):
15 | return torch.cat([pil2tensor(img) for img in image], dim=0)
16 |
17 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
18 |
19 | #----------------------------------------------------------------------------
20 | # 添加一个辅助函数,用于交换宽度和高度
21 | def swap_width_height(width, height):
22 | return height, width
23 |
24 | #----------------------------------------------------------------------------
25 | import logging
26 | import re
27 | import os
28 |
29 | base_log_level = logging.DEBUG if os.environ.get("MTB_DEBUG") else logging.INFO
30 |
31 |
32 | # Custom object that discards the output
33 | class NullWriter:
34 | def write(self, text):
35 | pass
36 |
37 |
38 | class Formatter(logging.Formatter):
39 | grey = "\x1b[38;20m"
40 | cyan = "\x1b[36;20m"
41 | purple = "\x1b[35;20m"
42 | yellow = "\x1b[33;20m"
43 | red = "\x1b[31;20m"
44 | bold_red = "\x1b[31;1m"
45 | reset = "\x1b[0m"
46 | # format = "%(asctime)s - [%(name)s] - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
47 | format = "[%(name)s] | %(levelname)s -> %(message)s"
48 |
49 | FORMATS = {
50 | logging.DEBUG: purple + format + reset,
51 | logging.INFO: cyan + format + reset,
52 | logging.WARNING: yellow + format + reset,
53 | logging.ERROR: red + format + reset,
54 | logging.CRITICAL: bold_red + format + reset,
55 | }
56 |
57 | def format(self, record):
58 | log_fmt = self.FORMATS.get(record.levelno)
59 | formatter = logging.Formatter(log_fmt)
60 | return formatter.format(record)
61 |
62 |
63 | def mklog(name, level=base_log_level):
64 | logger = logging.getLogger(name)
65 | logger.setLevel(level)
66 |
67 | for handler in logger.handlers:
68 | logger.removeHandler(handler)
69 |
70 | ch = logging.StreamHandler()
71 | ch.setLevel(level)
72 | ch.setFormatter(Formatter())
73 | logger.addHandler(ch)
74 |
75 | # Disable log propagation
76 | logger.propagate = False
77 |
78 | return logger
79 |
80 |
81 | # - The main app logger
82 | log = mklog(__package__, base_log_level)
83 |
84 |
85 | def log_user(arg):
86 | print("\033[34mComfy MTB Utils:\033[0m {arg}")
87 |
88 |
89 | def get_summary(docstring):
90 | return docstring.strip().split("\n\n", 1)[0]
91 |
92 |
93 | def blue_text(text):
94 | return f"\033[94m{text}\033[0m"
95 |
96 |
97 | def cyan_text(text):
98 | return f"\033[96m{text}\033[0m"
99 |
100 |
101 | def get_label(label):
102 | words = re.findall(r"(?:^|[A-Z])[a-z]*", label)
103 | return " ".join(words).strip()
104 |
105 | # 禁用 aiohttp 的访问日志记录器
106 | logging.getLogger('aiohttp.access').disabled = True
107 | #----------------------------------------------------------------------------
108 | def bbox_dim(bbox):
109 | left, upper, right, lower = bbox
110 | width = right - left
111 | height = lower - upper
112 | return width, height
113 |
114 | #----------------------------------------------------------------------------
115 | class Text_Image_Frame_Zho:
116 |
117 | fonts = {}
118 |
119 | def __init__(self):
120 | # - This is executed when the graph is executed, we could conditionaly reload fonts there
121 | pass
122 |
123 | @classmethod
124 | def CACHE_FONTS(cls):
125 | font_extensions = ["*.ttf", "*.otf", "*.woff", "*.woff2", "*.eot"]
126 | fonts = []
127 |
128 | for extension in font_extensions:
129 | fonts.extend(comfy_dir.glob(f"**/{extension}"))
130 |
131 | if not fonts:
132 | log.warn(
133 | "> No fonts found in the comfy folder, place at least one font file somewhere in ComfyUI's hierarchy"
134 | )
135 | else:
136 | log.debug(f"> Found {len(fonts)} fonts")
137 |
138 | for font in fonts:
139 | log.debug(f"Adding font {font}")
140 | cls.fonts[font.stem] = font.as_posix()
141 |
142 | @classmethod
143 | def INPUT_TYPES(cls):
144 | if not cls.fonts:
145 | cls.CACHE_FONTS()
146 | else:
147 | log.debug(f"Using cached fonts (count: {len(cls.fonts)})")
148 | return {
149 | "required": {
150 | "number": (
151 | "STRING",
152 | {"default": "0"},
153 | ),
154 | # 增加frame参数
155 | "frame": (
156 | "INT",
157 | {"default": 1, "min": 1, "max": 100, "step": 1},
158 | ),
159 | # 增加step参数
160 | "step": (
161 | "INT",
162 | {"default": 1, "min": 1, "max": 100, "step": 1},
163 | ),
164 | "selected_font": ((sorted(cls.fonts.keys())),),
165 | "align": (["left", "center", "right"],
166 | ),
167 | "wrap": (
168 | "INT",
169 | {"default": 10, "min": 0, "max": 8096, "step": 1},
170 | ),
171 | "font_size": (
172 | "INT",
173 | {"default": 50, "min": 1, "max": 2500, "step": 1},
174 | ),
175 | "color": (
176 | "COLOR",
177 | {"default": "red"},
178 | ),
179 | "outline_size": (
180 | "INT",
181 | {"default": 0, "min": 0, "max": 8096, "step": 1},
182 | ),
183 | "outline_color": (
184 | "COLOR",
185 | {"default": "blue"}, # 设置默认的描边颜色
186 | ),
187 | "margin_x": (
188 | "INT",
189 | {"default": 0, "min": 0, "max": 8096, "step": 1},
190 | ),
191 | "margin_y": (
192 | "INT",
193 | {"default": 0, "min": 0, "max": 8096, "step": 1},
194 | ),
195 | "width": (
196 | "INT",
197 | {"default": 512, "min": 1, "max": 8096, "step": 1},
198 | ),
199 | "height": (
200 | "INT",
201 | {"default": 512, "min": 1, "max": 8096, "step": 1},
202 | ),
203 | "swap": ("BOOLEAN", {"default": False}), # 添加交换宽度和高度的按钮
204 | }
205 | }
206 |
207 | RETURN_TYPES = ("IMAGE",)
208 | RETURN_NAMES = ("image",)
209 | FUNCTION = "text_to_image_frame"
210 | CATEGORY = "Zho模块组/text"
211 |
212 | def text_to_image(
213 | self, number, selected_font, align, wrap, font_size, width, height, color, outline_size, outline_color, margin_x, margin_y, swap=False
214 | ):
215 | from PIL import Image, ImageDraw, ImageFont
216 | import textwrap
217 |
218 | # 如果用户选择交换宽度和高度,则调用交换函数
219 | if swap:
220 | width, height = swap_width_height(width, height)
221 |
222 | font_path = self.fonts[selected_font]
223 | (_, top, _, _) = ImageFont.truetype(font_path, font_size).getbbox(number)
224 | font = cast(ImageFont.FreeTypeFont, ImageFont.truetype(font_path, font_size))
225 | if wrap == 0:
226 | wrap = width / font_size
227 | wrap = int(wrap)
228 | lines = textwrap.wrap(number, width=wrap)
229 | log.debug(f"Lines: {lines}")
230 | line_height = bbox_dim(font.getbbox("hg"))[1]
231 | img_height = height # line_height * len(lines)
232 | img_width = width # max(font.getsize(line)[0] for line in lines)
233 |
234 | img = Image.new("RGBA", (img_width, img_height), (0, 0, 0, 0))
235 | draw = ImageDraw.Draw(img)
236 |
237 | # 初始化 y_text
238 | y_text = margin_y + outline_size - top
239 |
240 | for line in lines:
241 | width, height = bbox_dim(font.getbbox(line))
242 |
243 | # 根据 align 参数计算文本的 x 坐标
244 | if align == "left":
245 | x_text = margin_x
246 | elif align == "center":
247 | x_text = (img_width - width) // 2
248 | elif align == "right":
249 | x_text = img_width - width - margin_x
250 | else:
251 | x_text = margin_x # 默认为左对齐
252 |
253 | draw.text(
254 | (x_text, y_text),
255 | text=line,
256 | fill=color,
257 | stroke_fill=outline_color,
258 | stroke_width=outline_size,
259 | font=font,
260 | )
261 | y_text += height
262 |
263 | return (pil2tensor(img),)
264 |
265 | def text_to_image_frame(self, number, frame, step, selected_font, align, wrap, font_size, width, height, color, outline_size, outline_color, margin_x, margin_y, swap=False):
266 | images = []
267 | for i in range(frame):
268 | current_text = str(int(number) + i * step) # 计算当前步的文本内容
269 | image = self.text_to_image(
270 | current_text, selected_font, align, wrap, font_size, width, height, color, outline_size, outline_color, margin_x, margin_y, swap
271 | )
272 | images.append(image[0]) # image[0] 是因为 text_to_image 返回的是元组
273 | s = torch.cat(images, dim=0)
274 | return (s,)
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 | #----------------------------------------------------------------------------
285 | NODE_CLASS_MAPPINGS = {
286 | "Text_Image_Frame_Zho": Text_Image_Frame_Zho,
287 | }
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import filecmp
4 | import shutil
5 | import __main__
6 |
7 |
8 | python = sys.executable
9 |
10 |
11 | extentions_folder = os.path.join(os.path.dirname(os.path.realpath(__main__.__file__)),
12 | "web" + os.sep + "extensions" + os.sep + "ZHO")
13 | javascript_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "mtb")
14 |
15 | if not os.path.exists(extentions_folder):
16 | print('Making the "web\extensions\ZHO" folder')
17 | os.mkdir(extentions_folder)
18 |
19 | result = filecmp.dircmp(javascript_folder, extentions_folder)
20 |
21 | if result.left_only or result.diff_files:
22 | print('Update to javascripts files detected')
23 | file_list = list(result.left_only)
24 | file_list.extend(x for x in result.diff_files if x not in file_list)
25 |
26 | for file in file_list:
27 | print(f'Copying {file} to extensions folder')
28 | src_file = os.path.join(javascript_folder, file)
29 | dst_file = os.path.join(extentions_folder, file)
30 | if os.path.exists(dst_file):
31 | os.remove(dst_file)
32 | #print("disabled")
33 | shutil.copy(src_file, dst_file)
34 |
35 |
36 | from .Zho_TextImage import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_TI
37 | from .Zho_RGB_Image import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_RGB
38 | from .Zho_ImageComposite import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_IC
39 | from .Zho_AlphaChanel import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_AC
40 | from .Zho_TextImage_frame import NODE_CLASS_MAPPINGS as NODE_CLASS_MAPPINGS_TIF
41 |
42 |
43 | # Combine the dictionaries
44 | NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS_TI, **NODE_CLASS_MAPPINGS_RGB, **NODE_CLASS_MAPPINGS_IC, **NODE_CLASS_MAPPINGS_AC, **NODE_CLASS_MAPPINGS_TIF}
45 |
46 |
47 | __all__ = ['NODE_CLASS_MAPPINGS']
48 |
--------------------------------------------------------------------------------
/font/Alkatra.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Alkatra.ttf
--------------------------------------------------------------------------------
/font/CALIBRI.TTF:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/CALIBRI.TTF
--------------------------------------------------------------------------------
/font/COMIC.TTF:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/COMIC.TTF
--------------------------------------------------------------------------------
/font/COMICI.TTF:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/COMICI.TTF
--------------------------------------------------------------------------------
/font/COMICZ.TTF:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/COMICZ.TTF
--------------------------------------------------------------------------------
/font/Merienda-Black.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-Black.ttf
--------------------------------------------------------------------------------
/font/Merienda-Bold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-Bold.ttf
--------------------------------------------------------------------------------
/font/Merienda-ExtraBold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-ExtraBold.ttf
--------------------------------------------------------------------------------
/font/Merienda-Light.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-Light.ttf
--------------------------------------------------------------------------------
/font/Merienda-Medium.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-Medium.ttf
--------------------------------------------------------------------------------
/font/Merienda-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-Regular.ttf
--------------------------------------------------------------------------------
/font/Merienda-SemiBold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-SemiBold.ttf
--------------------------------------------------------------------------------
/font/Merienda-VariableFont_wght.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/Merienda-VariableFont_wght.ttf
--------------------------------------------------------------------------------
/font/OverlockSC-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZHO-ZHO-ZHO/ComfyUI-Text_Image-Composite/47c1531abd59a5315aa0092536867745711ff897/font/OverlockSC-Regular.ttf
--------------------------------------------------------------------------------
/mtb/comfy_shared.js:
--------------------------------------------------------------------------------
1 | /**
2 | * File: comfy_shared.js
3 | * Project: comfy_mtb
4 | * Author: Mel Massadian
5 | *
6 | * Copyright (c) 2023 Mel Massadian
7 | *
8 | */
9 |
10 | import { app } from '../../scripts/app.js'
11 |
12 | export const log = (...args) => {
13 | if (window.MTB?.DEBUG) {
14 | console.debug(...args)
15 | }
16 | }
17 |
18 | //- WIDGET UTILS
19 | export const CONVERTED_TYPE = 'converted-widget'
20 |
21 | export const hasWidgets = (node) => {
22 | if (!node.widgets || !node.widgets?.[Symbol.iterator]) {
23 | return false
24 | }
25 | return true
26 | }
27 |
28 | export const cleanupNode = (node) => {
29 | if (!hasWidgets(node)) {
30 | return
31 | }
32 |
33 | for (const w of node.widgets) {
34 | if (w.canvas) {
35 | w.canvas.remove()
36 | }
37 | if (w.inputEl) {
38 | w.inputEl.remove()
39 | }
40 | // calls the widget remove callback
41 | w.onRemoved?.()
42 | }
43 | }
44 |
45 | export function offsetDOMWidget(
46 | widget,
47 | ctx,
48 | node,
49 | widgetWidth,
50 | widgetY,
51 | height
52 | ) {
53 | const margin = 10
54 | const elRect = ctx.canvas.getBoundingClientRect()
55 | const transform = new DOMMatrix()
56 | .scaleSelf(
57 | elRect.width / ctx.canvas.width,
58 | elRect.height / ctx.canvas.height
59 | )
60 | .multiplySelf(ctx.getTransform())
61 | .translateSelf(margin, margin + widgetY)
62 |
63 | const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)
64 | Object.assign(widget.inputEl.style, {
65 | transformOrigin: '0 0',
66 | transform: scale,
67 | left: `${transform.a + transform.e}px`,
68 | top: `${transform.d + transform.f}px`,
69 | width: `${widgetWidth - margin * 2}px`,
70 | // height: `${(widget.parent?.inputHeight || 32) - (margin * 2)}px`,
71 | height: `${(height || widget.parent?.inputHeight || 32) - margin * 2}px`,
72 |
73 | position: 'absolute',
74 | background: !node.color ? '' : node.color,
75 | color: !node.color ? '' : 'white',
76 | zIndex: 5, //app.graph._nodes.indexOf(node),
77 | })
78 | }
79 |
80 | /**
81 | * Extracts the type and link type from a widget config object.
82 | * @param {*} config
83 | * @returns
84 | */
85 | export function getWidgetType(config) {
86 | // Special handling for COMBO so we restrict links based on the entries
87 | let type = config?.[0]
88 | let linkType = type
89 | if (type instanceof Array) {
90 | type = 'COMBO'
91 | linkType = linkType.join(',')
92 | }
93 | return { type, linkType }
94 | }
95 |
96 | export const dynamic_connection = (
97 | node,
98 | index,
99 | connected,
100 | connectionPrefix = 'input_',
101 | connectionType = 'PSDLAYER'
102 | ) => {
103 | // remove all non connected inputs
104 | if (!connected && node.inputs.length > 1) {
105 | log(`Removing input ${index} (${node.inputs[index].name})`)
106 | if (node.widgets) {
107 | const w = node.widgets.find((w) => w.name === node.inputs[index].name)
108 | if (w) {
109 | w.onRemoved?.()
110 | node.widgets.length = node.widgets.length - 1
111 | }
112 | }
113 | node.removeInput(index)
114 |
115 | // make inputs sequential again
116 | for (let i = 0; i < node.inputs.length; i++) {
117 | node.inputs[i].label = `${connectionPrefix}${i + 1}`
118 | }
119 | }
120 |
121 | // add an extra input
122 | if (node.inputs[node.inputs.length - 1].link != undefined) {
123 | log(
124 | `Adding input ${node.inputs.length + 1} (${connectionPrefix}${
125 | node.inputs.length + 1
126 | })`
127 | )
128 |
129 | node.addInput(
130 | `${connectionPrefix}${node.inputs.length + 1}`,
131 | connectionType
132 | )
133 | }
134 | }
135 |
136 | /**
137 | * Appends a callback to the extra menu options of a given node type.
138 | * @param {*} nodeType
139 | * @param {*} cb
140 | */
141 | export function addMenuHandler(nodeType, cb) {
142 | const getOpts = nodeType.prototype.getExtraMenuOptions
143 | nodeType.prototype.getExtraMenuOptions = function () {
144 | const r = getOpts.apply(this, arguments)
145 | cb.apply(this, arguments)
146 | return r
147 | }
148 | }
149 |
150 | export function hideWidget(node, widget, suffix = '') {
151 | widget.origType = widget.type
152 | widget.hidden = true
153 | widget.origComputeSize = widget.computeSize
154 | widget.origSerializeValue = widget.serializeValue
155 | widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
156 | widget.type = CONVERTED_TYPE + suffix
157 | widget.serializeValue = () => {
158 | // Prevent serializing the widget if we have no input linked
159 | const { link } = node.inputs.find((i) => i.widget?.name === widget.name)
160 | if (link == null) {
161 | return undefined
162 | }
163 | return widget.origSerializeValue
164 | ? widget.origSerializeValue()
165 | : widget.value
166 | }
167 |
168 | // Hide any linked widgets, e.g. seed+seedControl
169 | if (widget.linkedWidgets) {
170 | for (const w of widget.linkedWidgets) {
171 | hideWidget(node, w, ':' + widget.name)
172 | }
173 | }
174 | }
175 |
176 | export function showWidget(widget) {
177 | widget.type = widget.origType
178 | widget.computeSize = widget.origComputeSize
179 | widget.serializeValue = widget.origSerializeValue
180 |
181 | delete widget.origType
182 | delete widget.origComputeSize
183 | delete widget.origSerializeValue
184 |
185 | // Hide any linked widgets, e.g. seed+seedControl
186 | if (widget.linkedWidgets) {
187 | for (const w of widget.linkedWidgets) {
188 | showWidget(w)
189 | }
190 | }
191 | }
192 |
193 | export function convertToWidget(node, widget) {
194 | showWidget(widget)
195 | const sz = node.size
196 | node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name))
197 |
198 | for (const widget of node.widgets) {
199 | widget.last_y -= LiteGraph.NODE_SLOT_HEIGHT
200 | }
201 |
202 | // Restore original size but grow if needed
203 | node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])
204 | }
205 |
206 | export function convertToInput(node, widget, config) {
207 | hideWidget(node, widget)
208 |
209 | const { linkType } = getWidgetType(config)
210 |
211 | // Add input and store widget config for creating on primitive node
212 | const sz = node.size
213 | node.addInput(widget.name, linkType, {
214 | widget: { name: widget.name, config },
215 | })
216 |
217 | for (const widget of node.widgets) {
218 | widget.last_y += LiteGraph.NODE_SLOT_HEIGHT
219 | }
220 |
221 | // Restore original size but grow if needed
222 | node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])
223 | }
224 |
225 | export function hideWidgetForGood(node, widget, suffix = '') {
226 | widget.origType = widget.type
227 | widget.origComputeSize = widget.computeSize
228 | widget.origSerializeValue = widget.serializeValue
229 | widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
230 | widget.type = CONVERTED_TYPE + suffix
231 | // widget.serializeValue = () => {
232 | // // Prevent serializing the widget if we have no input linked
233 | // const w = node.inputs?.find((i) => i.widget?.name === widget.name);
234 | // if (w?.link == null) {
235 | // return undefined;
236 | // }
237 | // return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
238 | // };
239 |
240 | // Hide any linked widgets, e.g. seed+seedControl
241 | if (widget.linkedWidgets) {
242 | for (const w of widget.linkedWidgets) {
243 | hideWidgetForGood(node, w, ':' + widget.name)
244 | }
245 | }
246 | }
247 |
248 | export function fixWidgets(node) {
249 | if (node.inputs) {
250 | for (const input of node.inputs) {
251 | log(input)
252 | if (input.widget || node.widgets) {
253 | // if (newTypes.includes(input.type)) {
254 | const matching_widget = node.widgets.find((w) => w.name === input.name)
255 | if (matching_widget) {
256 | // if (matching_widget.hidden) {
257 | // log(`Already hidden skipping ${matching_widget.name}`)
258 | // continue
259 | // }
260 | const w = node.widgets.find((w) => w.name === matching_widget.name)
261 | if (w && w.type != CONVERTED_TYPE) {
262 | log(w)
263 | log(`hidding ${w.name}(${w.type}) from ${node.type}`)
264 | log(node)
265 | hideWidget(node, w)
266 | } else {
267 | log(`converting to widget ${w}`)
268 |
269 | convertToWidget(node, input)
270 | }
271 | }
272 | }
273 | }
274 | }
275 | }
276 | export function inner_value_change(widget, value, event = undefined) {
277 | if (widget.type == 'number' || widget.type == 'BBOX') {
278 | value = Number(value)
279 | } else if (widget.type == 'BOOL') {
280 | value = Boolean(value)
281 | }
282 | widget.value = value
283 | if (
284 | widget.options &&
285 | widget.options.property &&
286 | node.properties[widget.options.property] !== undefined
287 | ) {
288 | node.setProperty(widget.options.property, value)
289 | }
290 | if (widget.callback) {
291 | widget.callback(widget.value, app.canvas, node, pos, event)
292 | }
293 | }
294 |
295 | //- COLOR UTILS
296 | export function isColorBright(rgb, threshold = 240) {
297 | const brightess = getBrightness(rgb)
298 | return brightess > threshold
299 | }
300 |
301 | function getBrightness(rgbObj) {
302 | return Math.round(
303 | (parseInt(rgbObj[0]) * 299 +
304 | parseInt(rgbObj[1]) * 587 +
305 | parseInt(rgbObj[2]) * 114) /
306 | 1000
307 | )
308 | }
309 |
310 | //- HTML / CSS UTILS
311 | export function defineClass(className, classStyles) {
312 | const styleSheets = document.styleSheets
313 |
314 | // Helper function to check if the class exists in a style sheet
315 | function classExistsInStyleSheet(styleSheet) {
316 | const rules = styleSheet.rules || styleSheet.cssRules
317 | for (const rule of rules) {
318 | if (rule.selectorText === `.${className}`) {
319 | return true
320 | }
321 | }
322 | return false
323 | }
324 |
325 | // Check if the class is already defined in any of the style sheets
326 | let classExists = false
327 | for (const styleSheet of styleSheets) {
328 | if (classExistsInStyleSheet(styleSheet)) {
329 | classExists = true
330 | break
331 | }
332 | }
333 |
334 | // If the class doesn't exist, add the new class definition to the first style sheet
335 | if (!classExists) {
336 | if (styleSheets[0].insertRule) {
337 | styleSheets[0].insertRule(`.${className} { ${classStyles} }`, 0)
338 | } else if (styleSheets[0].addRule) {
339 | styleSheets[0].addRule(`.${className}`, classStyles, 0)
340 | }
341 | }
342 | }
343 |
--------------------------------------------------------------------------------
/mtb/debug.js:
--------------------------------------------------------------------------------
1 | /**
2 | * File: debug.js
3 | * Project: comfy_mtb
4 | * Author: Mel Massadian
5 | *
6 | * Copyright (c) 2023 Mel Massadian
7 | *
8 | */
9 |
10 | import { app } from '../../scripts/app.js'
11 |
12 | import * as shared from './comfy_shared.js'
13 | import { log } from './comfy_shared.js'
14 | import { MtbWidgets } from './mtb_widgets.js'
15 |
16 | // TODO: respect inputs order...
17 |
18 | function escapeHtml(unsafe) {
19 | return unsafe
20 | .replace(/&/g, '&')
21 | .replace(//g, '>')
23 | .replace(/"/g, '"')
24 | .replace(/'/g, ''')
25 | }
26 | app.registerExtension({
27 | name: 'mtb.Debug',
28 | async beforeRegisterNodeDef(nodeType, nodeData, app) {
29 | if (nodeData.name === 'Debug (mtb)') {
30 | const onConnectionsChange = nodeType.prototype.onConnectionsChange
31 | nodeType.prototype.onConnectionsChange = function (
32 | type,
33 | index,
34 | connected,
35 | link_info
36 | ) {
37 | const r = onConnectionsChange
38 | ? onConnectionsChange.apply(this, arguments)
39 | : undefined
40 | // TODO: remove all widgets on disconnect once computed
41 | shared.dynamic_connection(this, index, connected, 'anything_', '*')
42 |
43 | //- infer type
44 | if (link_info) {
45 | const fromNode = this.graph._nodes.find(
46 | (otherNode) => otherNode.id == link_info.origin_id
47 | )
48 | const type = fromNode.outputs[link_info.origin_slot].type
49 | this.inputs[index].type = type
50 | // this.inputs[index].label = type.toLowerCase()
51 | }
52 | //- restore dynamic input
53 | if (!connected) {
54 | this.inputs[index].type = '*'
55 | this.inputs[index].label = `anything_${index + 1}`
56 | }
57 | }
58 |
59 | const onExecuted = nodeType.prototype.onExecuted
60 | nodeType.prototype.onExecuted = function (message) {
61 | onExecuted?.apply(this, arguments)
62 |
63 | const prefix = 'anything_'
64 |
65 | if (this.widgets) {
66 | // const pos = this.widgets.findIndex((w) => w.name === "anything_1");
67 | // if (pos !== -1) {
68 | for (let i = 0; i < this.widgets.length; i++) {
69 | this.widgets[i].onRemoved?.()
70 | }
71 | this.widgets.length = 0
72 | }
73 | let widgetI = 1
74 | if (message.text) {
75 | for (const txt of message.text) {
76 | const w = this.addCustomWidget(
77 | MtbWidgets.DEBUG_STRING(`${prefix}_${widgetI}`, escapeHtml(txt))
78 | )
79 | w.parent = this
80 | widgetI++
81 | }
82 | }
83 | if (message.b64_images) {
84 | for (const img of message.b64_images) {
85 | const w = this.addCustomWidget(
86 | MtbWidgets.DEBUG_IMG(`${prefix}_${widgetI}`, img)
87 | )
88 | w.parent = this
89 | widgetI++
90 | }
91 | // this.onResize?.(this.size);
92 | // this.resize?.(this.size)
93 | }
94 |
95 | this.setSize(this.computeSize())
96 |
97 | this.onRemoved = function () {
98 | // When removing this node we need to remove the input from the DOM
99 | for (let y in this.widgets) {
100 | if (this.widgets[y].canvas) {
101 | this.widgets[y].canvas.remove()
102 | }
103 | this.widgets[y].onRemoved?.()
104 | }
105 | }
106 | }
107 | }
108 | },
109 | })
110 |
--------------------------------------------------------------------------------
/mtb/mtb_widgets.js:
--------------------------------------------------------------------------------
1 | /**
2 | * File: mtb_widgets.js
3 | * Project: comfy_mtb
4 | * Author: Mel Massadian
5 | *
6 | * Copyright (c) 2023 Mel Massadian
7 | *
8 | */
9 |
10 | import { app } from '../../scripts/app.js'
11 | import { api } from '../../scripts/api.js'
12 |
13 | import parseCss from './parse-css.js'
14 | import * as shared from './comfy_shared.js'
15 | import { log } from './comfy_shared.js'
16 |
17 | const newTypes = [, /*'BOOL'*/ 'COLOR', 'BBOX']
18 |
19 | const withFont = (ctx, font, cb) => {
20 | const oldFont = ctx.font
21 | ctx.font = font
22 | cb()
23 | ctx.font = oldFont
24 | }
25 |
26 | const calculateTextDimensions = (ctx, value, width, fontSize = 16) => {
27 | const words = value.split(' ')
28 | const lines = []
29 | let currentLine = ''
30 | for (const word of words) {
31 | const testLine = currentLine.length === 0 ? word : `${currentLine} ${word}`
32 | const testWidth = ctx.measureText(testLine).width
33 | if (testWidth > width) {
34 | lines.push(currentLine)
35 | currentLine = word
36 | } else {
37 | currentLine = testLine
38 | }
39 | }
40 | if (lines.length === 0) lines.push(value)
41 | const textHeight = (lines.length + 1) * fontSize
42 | const maxLineWidth = lines.reduce(
43 | (maxWidth, line) => Math.max(maxWidth, ctx.measureText(line).width),
44 | 0
45 | )
46 | return { textHeight, maxLineWidth }
47 | }
48 |
49 | export const MtbWidgets = {
50 | BBOX: (key, val) => {
51 | /** @type {import("./types/litegraph").IWidget} */
52 | const widget = {
53 | name: key,
54 | type: 'BBOX',
55 | // options: val,
56 | y: 0,
57 | value: val?.default || [0, 0, 0, 0],
58 | options: {},
59 |
60 | draw: function (ctx, node, widget_width, widgetY, height) {
61 | const hide = this.type !== 'BBOX' && app.canvas.ds.scale > 0.5
62 |
63 | const show_text = true
64 | const outline_color = LiteGraph.WIDGET_OUTLINE_COLOR
65 | const background_color = LiteGraph.WIDGET_BGCOLOR
66 | const text_color = LiteGraph.WIDGET_TEXT_COLOR
67 | const secondary_text_color = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR
68 | const H = LiteGraph.NODE_WIDGET_HEIGHT
69 |
70 | let margin = 15
71 | let numWidgets = 4 // Number of stacked widgets
72 |
73 | if (hide) return
74 |
75 | for (let i = 0; i < numWidgets; i++) {
76 | let currentY = widgetY + i * (H + margin) // Adjust Y position for each widget
77 |
78 | ctx.textAlign = 'left'
79 | ctx.strokeStyle = outline_color
80 | ctx.fillStyle = background_color
81 | ctx.beginPath()
82 | if (show_text)
83 | ctx.roundRect(margin, currentY, widget_width - margin * 2, H, [
84 | H * 0.5,
85 | ])
86 | else ctx.rect(margin, currentY, widget_width - margin * 2, H)
87 | ctx.fill()
88 | if (show_text) {
89 | if (!this.disabled) ctx.stroke()
90 | ctx.fillStyle = text_color
91 | if (!this.disabled) {
92 | ctx.beginPath()
93 | ctx.moveTo(margin + 16, currentY + 5)
94 | ctx.lineTo(margin + 6, currentY + H * 0.5)
95 | ctx.lineTo(margin + 16, currentY + H - 5)
96 | ctx.fill()
97 | ctx.beginPath()
98 | ctx.moveTo(widget_width - margin - 16, currentY + 5)
99 | ctx.lineTo(widget_width - margin - 6, currentY + H * 0.5)
100 | ctx.lineTo(widget_width - margin - 16, currentY + H - 5)
101 | ctx.fill()
102 | }
103 | ctx.fillStyle = secondary_text_color
104 | ctx.fillText(
105 | this.label || this.name,
106 | margin * 2 + 5,
107 | currentY + H * 0.7
108 | )
109 | ctx.fillStyle = text_color
110 | ctx.textAlign = 'right'
111 |
112 | ctx.fillText(
113 | Number(this.value).toFixed(
114 | this.options?.precision !== undefined
115 | ? this.options.precision
116 | : 3
117 | ),
118 | widget_width - margin * 2 - 20,
119 | currentY + H * 0.7
120 | )
121 | }
122 | }
123 | },
124 | mouse: function (event, pos, node) {
125 | let old_value = this.value
126 | let x = pos[0] - node.pos[0]
127 | let y = pos[1] - node.pos[1]
128 | let width = node.size[0]
129 | let H = LiteGraph.NODE_WIDGET_HEIGHT
130 | let margin = 5
131 | let numWidgets = 4 // Number of stacked widgets
132 |
133 | for (let i = 0; i < numWidgets; i++) {
134 | let currentY = y + i * (H + margin) // Adjust Y position for each widget
135 |
136 | if (
137 | event.type == LiteGraph.pointerevents_method + 'move' &&
138 | this.type == 'BBOX'
139 | ) {
140 | if (event.deltaX)
141 | this.value += event.deltaX * 0.1 * (this.options?.step || 1)
142 | if (this.options.min != null && this.value < this.options.min) {
143 | this.value = this.options.min
144 | }
145 | if (this.options.max != null && this.value > this.options.max) {
146 | this.value = this.options.max
147 | }
148 | } else if (event.type == LiteGraph.pointerevents_method + 'down') {
149 | let values = this.options?.values
150 | if (values && values.constructor === Function) {
151 | values = this.options.values(w, node)
152 | }
153 | let values_list = null
154 |
155 | let delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0
156 | if (this.type == 'BBOX') {
157 | this.value += delta * 0.1 * (this.options.step || 1)
158 | if (this.options.min != null && this.value < this.options.min) {
159 | this.value = this.options.min
160 | }
161 | if (this.options.max != null && this.value > this.options.max) {
162 | this.value = this.options.max
163 | }
164 | } else if (delta) {
165 | //clicked in arrow, used for combos
166 | let index = -1
167 | this.last_mouseclick = 0 //avoids dobl click event
168 | if (values.constructor === Object)
169 | index = values_list.indexOf(String(this.value)) + delta
170 | else index = values_list.indexOf(this.value) + delta
171 | if (index >= values_list.length) {
172 | index = values_list.length - 1
173 | }
174 | if (index < 0) {
175 | index = 0
176 | }
177 | if (values.constructor === Array) this.value = values[index]
178 | else this.value = index
179 | }
180 | } //end mousedown
181 | else if (
182 | event.type == LiteGraph.pointerevents_method + 'up' &&
183 | this.type == 'BBOX'
184 | ) {
185 | let delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0
186 | if (event.click_time < 200 && delta == 0) {
187 | this.prompt(
188 | 'Value',
189 | this.value,
190 | function (v) {
191 | // check if v is a valid equation or a number
192 | if (/^[0-9+\-*/()\s]+|\d+\.\d+$/.test(v)) {
193 | try {
194 | //solve the equation if possible
195 | v = eval(v)
196 | } catch (e) {}
197 | }
198 | this.value = Number(v)
199 | shared.inner_value_change(this, this.value, event)
200 | }.bind(w),
201 | event
202 | )
203 | }
204 | }
205 |
206 | if (old_value != this.value)
207 | setTimeout(
208 | function () {
209 | shared.inner_value_change(this, this.value, event)
210 | }.bind(this),
211 | 20
212 | )
213 |
214 | app.canvas.setDirty(true)
215 | }
216 | },
217 | computeSize: function (width) {
218 | return [width, LiteGraph.NODE_WIDGET_HEIGHT * 4]
219 | },
220 | // onDrawBackground: function (ctx) {
221 | // if (!this.flags.collapsed) return;
222 | // this.inputEl.style.display = "block";
223 | // this.inputEl.style.top = this.graphcanvas.offsetTop + this.pos[1] + "px";
224 | // this.inputEl.style.left = this.graphcanvas.offsetLeft + this.pos[0] + "px";
225 | // },
226 | // onInputChange: function (e) {
227 | // const property = e.target.dataset.property;
228 | // const bbox = this.getInputData(0);
229 | // if (!bbox) return;
230 | // bbox[property] = parseFloat(e.target.value);
231 | // this.setOutputData(0, bbox);
232 | // }
233 | }
234 |
235 | widget.desc = 'Represents a Bounding Box with x, y, width, and height.'
236 | return widget
237 | },
238 |
239 | COLOR: (key, val, compute = false) => {
240 | /** @type {import("/types/litegraph").IWidget} */
241 | const widget = {}
242 | widget.y = 0
243 | widget.name = key
244 | widget.type = 'COLOR'
245 | widget.options = { default: '#ff0000' }
246 | widget.value = val || '#ff0000'
247 | widget.draw = function (ctx, node, widgetWidth, widgetY, height) {
248 | const hide = this.type !== 'COLOR' && app.canvas.ds.scale > 0.5
249 | if (hide) {
250 | return
251 | }
252 | const border = 3
253 | ctx.fillStyle = '#000'
254 | ctx.fillRect(0, widgetY, widgetWidth, height)
255 | ctx.fillStyle = this.value
256 | ctx.fillRect(
257 | border,
258 | widgetY + border,
259 | widgetWidth - border * 2,
260 | height - border * 2
261 | )
262 | const color = parseCss(this.value.default || this.value)
263 | if (!color) {
264 | return
265 | }
266 | ctx.fillStyle = shared.isColorBright(color.values, 125) ? '#000' : '#fff'
267 |
268 | ctx.font = '14px Arial'
269 | ctx.textAlign = 'center'
270 | ctx.fillText(this.name, widgetWidth * 0.5, widgetY + 14)
271 | }
272 | widget.mouse = function (e, pos, node) {
273 | if (e.type === 'pointerdown') {
274 | const widgets = node.widgets.filter((w) => w.type === 'COLOR')
275 |
276 | for (const w of widgets) {
277 | // color picker
278 | const rect = [w.last_y, w.last_y + 32]
279 | if (pos[1] > rect[0] && pos[1] < rect[1]) {
280 | const picker = document.createElement('input')
281 | picker.type = 'color'
282 | picker.value = this.value
283 |
284 | picker.style.position = 'absolute'
285 | picker.style.left = '999999px' //(window.innerWidth / 2) + "px";
286 | picker.style.top = '999999px' //(window.innerHeight / 2) + "px";
287 |
288 | document.body.appendChild(picker)
289 |
290 | picker.addEventListener('change', () => {
291 | this.value = picker.value
292 | node.graph._version++
293 | node.setDirtyCanvas(true, true)
294 | picker.remove()
295 | })
296 |
297 | picker.click()
298 | }
299 | }
300 | }
301 | }
302 | widget.computeSize = function (width) {
303 | return [width, 32]
304 | }
305 |
306 | return widget
307 | },
308 |
309 | DEBUG_IMG: (name, val) => {
310 | const w = {
311 | name,
312 | type: 'image',
313 | value: val,
314 | draw: function (ctx, node, widgetWidth, widgetY, height) {
315 | const [cw, ch] = this.computeSize(widgetWidth)
316 | shared.offsetDOMWidget(this, ctx, node, widgetWidth, widgetY, ch)
317 | },
318 | computeSize: function (width) {
319 | const ratio = this.inputRatio || 1
320 | if (width) {
321 | return [width, width / ratio + 4]
322 | }
323 | return [128, 128]
324 | },
325 | onRemoved: function () {
326 | if (this.inputEl) {
327 | this.inputEl.remove()
328 | }
329 | },
330 | }
331 |
332 | w.inputEl = document.createElement('img')
333 | w.inputEl.src = w.value
334 | w.inputEl.onload = function () {
335 | w.inputRatio = w.inputEl.naturalWidth / w.inputEl.naturalHeight
336 | }
337 | document.body.appendChild(w.inputEl)
338 | return w
339 | },
340 | DEBUG_STRING: (name, val) => {
341 | const fontSize = 16
342 | const w = {
343 | name,
344 | type: 'debug_text',
345 |
346 | draw: function (ctx, node, widgetWidth, widgetY, height) {
347 | // const [cw, ch] = this.computeSize(widgetWidth)
348 | shared.offsetDOMWidget(this, ctx, node, widgetWidth, widgetY, height)
349 | },
350 | computeSize(width) {
351 | if (!this.value) {
352 | return [32, 32]
353 | }
354 | if (!width) {
355 | console.debug(`No width ${this.parent.size}`)
356 | }
357 | let dimensions
358 | withFont(app.ctx, `${fontSize}px monospace`, () => {
359 | dimensions = calculateTextDimensions(app.ctx, this.value, width)
360 | })
361 | const widgetWidth = Math.max(
362 | width || this.width || 32,
363 | dimensions.maxLineWidth
364 | )
365 | const widgetHeight = dimensions.textHeight * 1.5
366 | return [widgetWidth, widgetHeight]
367 | },
368 | onRemoved: function () {
369 | if (this.inputEl) {
370 | this.inputEl.remove()
371 | }
372 | },
373 | get value() {
374 | return this.inputEl.innerHTML
375 | },
376 | set value(val) {
377 | this.inputEl.innerHTML = val
378 | this.parent?.setSize?.(this.parent?.computeSize())
379 | },
380 | }
381 |
382 | w.inputEl = document.createElement('p')
383 | w.inputEl.style = `
384 | text-align: center;
385 | font-size: ${fontSize}px;
386 | color: var(--input-text);
387 | line-height: 0;
388 | font-family: monospace;
389 | `
390 | w.value = val
391 | document.body.appendChild(w.inputEl)
392 |
393 | return w
394 | },
395 | }
396 |
397 | /**
398 | * @returns {import("./types/comfy").ComfyExtension} extension
399 | */
400 | const mtb_widgets = {
401 | name: 'mtb.widgets',
402 |
403 | init: async () => {
404 | log('Registering mtb.widgets')
405 | try {
406 | const res = await api.fetchApi('/mtb/debug')
407 | const msg = await res.json()
408 | if (!window.MTB) {
409 | window.MTB = {}
410 | }
411 | window.MTB.DEBUG = msg.enabled
412 | } catch (e) {
413 | console.error('Error:', error)
414 | }
415 | },
416 |
417 | setup: () => {
418 | app.ui.settings.addSetting({
419 | id: 'mtb.Debug.enabled',
420 | name: '[mtb] Enable Debug (py and js)',
421 | type: 'boolean',
422 | defaultValue: false,
423 |
424 | tooltip:
425 | 'This will enable debug messages in the console and in the python console respectively',
426 | attrs: {
427 | style: {
428 | fontFamily: 'monospace',
429 | },
430 | },
431 | async onChange(value) {
432 | if (value) {
433 | console.log('Enabled DEBUG mode')
434 | }
435 | if (!window.MTB) {
436 | window.MTB = {}
437 | }
438 | window.MTB.DEBUG = value
439 | await api
440 | .fetchApi('/mtb/debug', {
441 | method: 'POST',
442 | body: JSON.stringify({
443 | enabled: value,
444 | }),
445 | })
446 | .then((response) => {})
447 | .catch((error) => {
448 | console.error('Error:', error)
449 | })
450 | },
451 | })
452 | },
453 |
454 | getCustomWidgets: function () {
455 | return {
456 | BOOL: (node, inputName, inputData, app) => {
457 | console.debug('Registering bool')
458 |
459 | return {
460 | widget: node.addCustomWidget(
461 | MtbWidgets.BOOL(inputName, inputData[1]?.default || false)
462 | ),
463 | minWidth: 150,
464 | minHeight: 30,
465 | }
466 | },
467 |
468 | COLOR: (node, inputName, inputData, app) => {
469 | console.debug('Registering color')
470 | return {
471 | widget: node.addCustomWidget(
472 | MtbWidgets.COLOR(inputName, inputData[1]?.default || '#ff0000')
473 | ),
474 | minWidth: 150,
475 | minHeight: 30,
476 | }
477 | },
478 | // BBOX: (node, inputName, inputData, app) => {
479 | // console.debug("Registering bbox")
480 | // return {
481 | // widget: node.addCustomWidget(MtbWidgets.BBOX(inputName, inputData[1]?.default || [0, 0, 0, 0])),
482 | // minWidth: 150,
483 | // minHeight: 30,
484 | // }
485 |
486 | // }
487 | }
488 | },
489 | /**
490 | * @param {import("./types/comfy").NodeType} nodeType
491 | * @param {import("./types/comfy").NodeDef} nodeData
492 | * @param {import("./types/comfy").App} app
493 | */
494 | async beforeRegisterNodeDef(nodeType, nodeData, app) {
495 | // const rinputs = nodeData.input?.required
496 |
497 | let has_custom = false
498 | if (nodeData.input && nodeData.input.required) {
499 | for (const i of Object.keys(nodeData.input.required)) {
500 | const input_type = nodeData.input.required[i][0]
501 |
502 | if (newTypes.includes(input_type)) {
503 | has_custom = true
504 | break
505 | }
506 | }
507 | }
508 | if (has_custom) {
509 | //- Add widgets on node creation
510 | const onNodeCreated = nodeType.prototype.onNodeCreated
511 | nodeType.prototype.onNodeCreated = function () {
512 | const r = onNodeCreated
513 | ? onNodeCreated.apply(this, arguments)
514 | : undefined
515 | this.serialize_widgets = true
516 | this.setSize?.(this.computeSize())
517 |
518 | this.onRemoved = function () {
519 | // When removing this node we need to remove the input from the DOM
520 | shared.cleanupNode(this)
521 | }
522 | return r
523 | }
524 |
525 | //- Extra menus
526 | const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions
527 | nodeType.prototype.getExtraMenuOptions = function (_, options) {
528 | const r = origGetExtraMenuOptions
529 | ? origGetExtraMenuOptions.apply(this, arguments)
530 | : undefined
531 | if (this.widgets) {
532 | let toInput = []
533 | let toWidget = []
534 | for (const w of this.widgets) {
535 | if (w.type === shared.CONVERTED_TYPE) {
536 | //- This is already handled by widgetinputs.js
537 | // toWidget.push({
538 | // content: `Convert ${w.name} to widget`,
539 | // callback: () => shared.convertToWidget(this, w),
540 | // });
541 | } else if (newTypes.includes(w.type)) {
542 | const config = nodeData?.input?.required[w.name] ||
543 | nodeData?.input?.optional?.[w.name] || [w.type, w.options || {}]
544 |
545 | toInput.push({
546 | content: `Convert ${w.name} to input`,
547 | callback: () => shared.convertToInput(this, w, config),
548 | })
549 | }
550 | }
551 | if (toInput.length) {
552 | options.push(...toInput, null)
553 | }
554 |
555 | if (toWidget.length) {
556 | options.push(...toWidget, null)
557 | }
558 | }
559 |
560 | return r
561 | }
562 | }
563 |
564 | //- Extending Python Nodes
565 | switch (nodeData.name) {
566 | case 'Psd Save (mtb)': {
567 | const onConnectionsChange = nodeType.prototype.onConnectionsChange
568 | nodeType.prototype.onConnectionsChange = function (
569 | type,
570 | index,
571 | connected,
572 | link_info
573 | ) {
574 | const r = onConnectionsChange
575 | ? onConnectionsChange.apply(this, arguments)
576 | : undefined
577 | shared.dynamic_connection(this, index, connected)
578 | return r
579 | }
580 | break
581 | }
582 | //TODO: remove this non sense
583 | case 'Get Batch From History (mtb)': {
584 | const onNodeCreated = nodeType.prototype.onNodeCreated
585 | nodeType.prototype.onNodeCreated = function () {
586 | const r = onNodeCreated
587 | ? onNodeCreated.apply(this, arguments)
588 | : undefined
589 | const internal_count = this.widgets.find(
590 | (w) => w.name === 'internal_count'
591 | )
592 | shared.hideWidgetForGood(this, internal_count)
593 | internal_count.afterQueued = function () {
594 | this.value++
595 | }
596 |
597 | return r
598 | }
599 |
600 | const onExecuted = nodeType.prototype.onExecuted
601 | nodeType.prototype.onExecuted = function (message) {
602 | const r = onExecuted ? onExecuted.apply(this, message) : undefined
603 | return r
604 | }
605 |
606 | break
607 | }
608 | case 'Save Gif (mtb)':
609 | case 'Save Animated Image (mtb)': {
610 | const onExecuted = nodeType.prototype.onExecuted
611 | nodeType.prototype.onExecuted = function (message) {
612 | const prefix = 'anything_'
613 | const r = onExecuted ? onExecuted.apply(this, message) : undefined
614 |
615 | if (this.widgets) {
616 | const pos = this.widgets.findIndex((w) => w.name === `${prefix}_0`)
617 | if (pos !== -1) {
618 | for (let i = pos; i < this.widgets.length; i++) {
619 | this.widgets[i].onRemoved?.()
620 | }
621 | this.widgets.length = pos
622 | }
623 |
624 | let imgURLs = []
625 | if (message) {
626 | if (message.gif) {
627 | imgURLs = imgURLs.concat(
628 | message.gif.map((params) => {
629 | return api.apiURL(
630 | '/view?' + new URLSearchParams(params).toString()
631 | )
632 | })
633 | )
634 | }
635 | if (message.apng) {
636 | imgURLs = imgURLs.concat(
637 | message.apng.map((params) => {
638 | return api.apiURL(
639 | '/view?' + new URLSearchParams(params).toString()
640 | )
641 | })
642 | )
643 | }
644 | let i = 0
645 | for (const img of imgURLs) {
646 | const w = this.addCustomWidget(
647 | MtbWidgets.DEBUG_IMG(`${prefix}_${i}`, img)
648 | )
649 | w.parent = this
650 | i++
651 | }
652 | }
653 | const onRemoved = this.onRemoved
654 | this.onRemoved = () => {
655 | shared.cleanupNode(this)
656 | return onRemoved?.()
657 | }
658 | }
659 | this.setSize?.(this.computeSize())
660 | return r
661 | }
662 |
663 | break
664 | }
665 | case 'Animation Builder (mtb)': {
666 | const onNodeCreated = nodeType.prototype.onNodeCreated
667 | nodeType.prototype.onNodeCreated = function () {
668 | const r = onNodeCreated
669 | ? onNodeCreated.apply(this, arguments)
670 | : undefined
671 |
672 | this.changeMode(LiteGraph.ALWAYS)
673 |
674 | const raw_iteration = this.widgets.find(
675 | (w) => w.name === 'raw_iteration'
676 | )
677 | const raw_loop = this.widgets.find((w) => w.name === 'raw_loop')
678 |
679 | const total_frames = this.widgets.find(
680 | (w) => w.name === 'total_frames'
681 | )
682 | const loop_count = this.widgets.find((w) => w.name === 'loop_count')
683 |
684 | shared.hideWidgetForGood(this, raw_iteration)
685 | shared.hideWidgetForGood(this, raw_loop)
686 |
687 | raw_iteration._value = 0
688 |
689 | const value_preview = this.addCustomWidget(
690 | MtbWidgets['DEBUG_STRING']('value_preview', 'Idle')
691 | )
692 | value_preview.parent = this
693 |
694 | const loop_preview = this.addCustomWidget(
695 | MtbWidgets['DEBUG_STRING']('loop_preview', 'Iteration: Idle')
696 | )
697 | loop_preview.parent = this
698 |
699 | const onReset = () => {
700 | raw_iteration.value = 0
701 | raw_loop.value = 0
702 |
703 | value_preview.value = 'Idle'
704 | loop_preview.value = 'Iteration: Idle'
705 |
706 | app.canvas.setDirty(true)
707 | }
708 |
709 | const reset_button = this.addWidget(
710 | 'button',
711 | `Reset`,
712 | 'reset',
713 | onReset
714 | )
715 |
716 | const run_button = this.addWidget('button', `Queue`, 'queue', () => {
717 | onReset() // this could maybe be a setting or checkbox
718 | app.queuePrompt(0, total_frames.value * loop_count.value)
719 | window.MTB?.notify?.(
720 | `Started a queue of ${total_frames.value} frames (for ${
721 | loop_count.value
722 | } loop, so ${total_frames.value * loop_count.value})`,
723 | 5000
724 | )
725 | })
726 |
727 | this.onRemoved = () => {
728 | shared.cleanupNode(this)
729 | app.canvas.setDirty(true)
730 | }
731 |
732 | raw_iteration.afterQueued = function () {
733 | this.value++
734 | raw_loop.value = Math.floor(this.value / total_frames.value)
735 |
736 | value_preview.value = `frame: ${
737 | raw_iteration.value % total_frames.value
738 | } / ${total_frames.value - 1}`
739 |
740 | if (raw_loop.value + 1 > loop_count.value) {
741 | loop_preview.value = 'Done 😎!'
742 | } else {
743 | loop_preview.value = `current loop: ${raw_loop.value + 1}/${
744 | loop_count.value
745 | }`
746 | }
747 | }
748 |
749 | return r
750 | }
751 |
752 | break
753 | }
754 | case 'Text Encore Frames (mtb)': {
755 | const onConnectionsChange = nodeType.prototype.onConnectionsChange
756 | nodeType.prototype.onConnectionsChange = function (
757 | type,
758 | index,
759 | connected,
760 | link_info
761 | ) {
762 | const r = onConnectionsChange
763 | ? onConnectionsChange.apply(this, arguments)
764 | : undefined
765 |
766 | shared.dynamic_connection(this, index, connected)
767 | return r
768 | }
769 | break
770 | }
771 | case 'Interpolate Clip Sequential (mtb)': {
772 | const onNodeCreated = nodeType.prototype.onNodeCreated
773 | nodeType.prototype.onNodeCreated = function () {
774 | const r = onNodeCreated
775 | ? onNodeCreated.apply(this, arguments)
776 | : undefined
777 | const addReplacement = () => {
778 | const input = this.addInput(
779 | `replacement_${this.widgets.length}`,
780 | 'STRING',
781 | ''
782 | )
783 | console.log(input)
784 | this.addWidget('STRING', `replacement_${this.widgets.length}`, '')
785 | }
786 | //- add
787 | this.addWidget('button', '+', 'add', function (value, widget, node) {
788 | console.log('Button clicked', value, widget, node)
789 | addReplacement()
790 | })
791 | //- remove
792 | this.addWidget(
793 | 'button',
794 | '-',
795 | 'remove',
796 | function (value, widget, node) {
797 | console.log(`Button clicked: ${value}`, widget, node)
798 | }
799 | )
800 |
801 | return r
802 | }
803 | break
804 | }
805 | case 'Styles Loader (mtb)': {
806 | const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions
807 | nodeType.prototype.getExtraMenuOptions = function (_, options) {
808 | const r = origGetExtraMenuOptions
809 | ? origGetExtraMenuOptions.apply(this, arguments)
810 | : undefined
811 |
812 | const getStyle = async (node) => {
813 | try {
814 | const getStyles = await api.fetchApi('/mtb/actions', {
815 | method: 'POST',
816 | body: JSON.stringify({
817 | name: 'getStyles',
818 | args:
819 | node.widgets && node.widgets[0].value
820 | ? node.widgets[0].value
821 | : '',
822 | }),
823 | })
824 |
825 | const output = await getStyles.json()
826 | return output?.result
827 | } catch (e) {
828 | console.error(e)
829 | }
830 | }
831 | const extracters = [
832 | {
833 | content: 'Extract Positive to Text node',
834 | callback: async () => {
835 | const style = await getStyle(this)
836 | if (style && style.length >= 1) {
837 | if (style[0]) {
838 | window.MTB?.notify?.(
839 | `Extracted positive from ${this.widgets[0].value}`
840 | )
841 | const tn = LiteGraph.createNode('Text box')
842 | app.graph.add(tn)
843 | tn.title = `${this.widgets[0].value} (Positive)`
844 | tn.widgets[0].value = style[0]
845 | } else {
846 | window.MTB?.notify?.(
847 | `No positive to extract for ${this.widgets[0].value}`
848 | )
849 | }
850 | }
851 | },
852 | },
853 | {
854 | content: 'Extract Negative to Text node',
855 | callback: async () => {
856 | const style = await getStyle(this)
857 | if (style && style.length >= 2) {
858 | if (style[1]) {
859 | window.MTB?.notify?.(
860 | `Extracted negative from ${this.widgets[0].value}`
861 | )
862 | const tn = LiteGraph.createNode('Text box')
863 | app.graph.add(tn)
864 | tn.title = `${this.widgets[0].value} (Negative)`
865 | tn.widgets[0].value = style[1]
866 | } else {
867 | window.MTB.notify(
868 | `No negative to extract for ${this.widgets[0].value}`
869 | )
870 | }
871 | }
872 | },
873 | },
874 | ]
875 | options.push(...extracters)
876 | }
877 |
878 | break
879 | }
880 | case 'Save Tensors (mtb)': {
881 | const onDrawBackground = nodeType.prototype.onDrawBackground
882 | nodeType.prototype.onDrawBackground = function (ctx, canvas) {
883 | const r = onDrawBackground
884 | ? onDrawBackground.apply(this, arguments)
885 | : undefined
886 | // // draw a circle on the top right of the node, with text inside
887 | // ctx.fillStyle = "#fff";
888 | // ctx.beginPath();
889 | // ctx.arc(this.size[0] - this.node_width * 0.5, this.size[1] - this.node_height * 0.5, this.node_width * 0.5, 0, Math.PI * 2);
890 | // ctx.fill();
891 |
892 | // ctx.fillStyle = "#000";
893 | // ctx.textAlign = "center";
894 | // ctx.font = "bold 12px Arial";
895 | // ctx.fillText("Save Tensors", this.size[0] - this.node_width * 0.5, this.size[1] - this.node_height * 0.5);
896 |
897 | return r
898 | }
899 | break
900 | }
901 | default: {
902 | break
903 | }
904 | }
905 | },
906 | }
907 |
908 | app.registerExtension(mtb_widgets)
909 |
--------------------------------------------------------------------------------
/mtb/parse-css.js:
--------------------------------------------------------------------------------
1 |
2 | // #region patterns
3 | const float = '-?\\d*(?:\\.\\d+)';
4 | export const number = `(${float}?)`;
5 | export const percentage = `(${float}?%)`;
6 | export const numberOrPercentage = `(${float}?%?)`;
7 | const clamp = (num, min, max) => Math.min(Math.max(min, num), max);
8 |
9 | const hexCharacters = 'a-f\\d';
10 | const match3or4Hex = `#?[${hexCharacters}]{3}[${hexCharacters}]?`;
11 | const match6or8Hex = `#?[${hexCharacters}]{6}([${hexCharacters}]{2})?`;
12 | const nonHexChars = new RegExp(`[^#${hexCharacters}]`, 'gi');
13 | const validHexSize = new RegExp(`^${match3or4Hex}$|^${match6or8Hex}$`, 'i');
14 |
15 |
16 | export const hex_pattern = new RegExp(/^#([a-f0-9]{3,4}|[a-f0-9]{4}(?:[a-f0-9]{2}){1,2})\b$/, "i");
17 |
18 | export const hsl3_pattern = new RegExp(`^
19 | hsla?\\(
20 | \\s*(-?\\d*(?:\\.\\d+)?(?:deg|rad|turn)?)\\s*,
21 | \\s*${percentage}\\s*,
22 | \\s*${percentage}\\s*
23 | (?:,\\s*${numberOrPercentage}\\s*)?
24 | \\)
25 | $
26 | `.replace(/\n|\s/g, ''))
27 |
28 | export const hsl4_pattern = new RegExp(`^
29 | hsla?\\(
30 | \\s*(-?\\d*(?:\\.\\d+)?(?:deg|rad|turn)?)\\s*
31 | \\s+${percentage}
32 | \\s+${percentage}
33 | \\s*(?:\\s*\\/\\s*${numberOrPercentage}\\s*)?
34 | \\)
35 | $
36 | `.replace(/\n|\s/g, ''))
37 |
38 | export const rgb3_pattern = new RegExp(`^
39 | rgba?\\(
40 | \\s*${number}\\s*,
41 | \\s*${number}\\s*,
42 | \\s*${number}\\s*
43 | (?:,\\s*${numberOrPercentage}\\s*)?
44 | \\)
45 | $
46 | `.replace(/\n|\s/g, ''))
47 |
48 | export const rgb4_pattern = new RegExp(`^
49 | rgba?\\(
50 | \\s*${number}
51 | \\s+${number}
52 | \\s+${number}
53 | \\s*(?:\\s*\\/\\s*${numberOrPercentage}\\s*)?
54 | \\)
55 | $
56 | `.replace(/\n|\s/g, ''));
57 |
58 | export const transparent_pattern = new RegExp(/^transparent$/, 'i');
59 | // #endregion
60 |
61 |
62 | // #region utils
63 |
64 |
65 | /* 500 => 255, -10 => 0, 128 => 128 */
66 | const parseRGB = (num) => {
67 | let n = num;
68 | if (typeof n !== 'number') {
69 | n = n.endsWith('%') ? (parseFloat(n) * 255) / 100 : parseFloat(n);
70 | }
71 | return clamp(Math.round(n), 0, 255);
72 | };
73 |
74 | /* 200 => 100, -100 => 0, 50 => 50 */
75 | const parsePercentage = (percentage) => clamp(parseFloat(percentage), 0, 100);
76 |
77 | /* '50%' => 5.0, 200 => 1, -10 => 0 */
78 | function parseAlpha(alpha) {
79 | let a = alpha;
80 | if (typeof a !== 'number') {
81 | a = a.endsWith('%') ? parseFloat(a) / 100 : parseFloat(a);
82 | }
83 | return clamp(a, 0, 1);
84 | }
85 |
86 | export function getHEX(hex) {
87 | const [r, g, b, a] = hex2Rgb(hex, { format: 'array' });
88 | return getRGB([null, ...[r, g, b, a]]);
89 | }
90 |
91 | export function getHSL([, h, s, l, a = 1]) {
92 | let hh = h;
93 | if (hh.endsWith('turn')) {
94 | hh = (parseFloat(hh) * 360) / 1;
95 | } else if (hh.endsWith('rad')) {
96 | hh = Math.round((parseFloat(hh) * 180) / Math.PI);
97 | } else {
98 | hh = parseFloat(hh);
99 | }
100 | return {
101 | type: 'hsl',
102 | values: [hh, parsePercentage(s), parsePercentage(l)],
103 | alpha: parseAlpha(a === null ? 1 : a)
104 | };
105 | }
106 |
107 | export function getRGB([, r, g, b, a = 1]) {
108 | return {
109 | type: 'rgb',
110 | values: [r, g, b].map(parseRGB),
111 | alpha: parseAlpha(a === null ? 1 : a)
112 | };
113 | }
114 | export function hex2Rgb(hex, options = {}) {
115 | if (typeof hex !== 'string' || nonHexChars.test(hex) || !validHexSize.test(hex)) {
116 | throw new TypeError('Expected a valid hex string');
117 | }
118 |
119 | hex = hex.replace(/^#/, '');
120 | let alphaFromHex = 1;
121 |
122 | if (hex.length === 8) {
123 | alphaFromHex = Number.parseInt(hex.slice(6, 8), 16) / 255;
124 | hex = hex.slice(0, 6);
125 | }
126 |
127 | if (hex.length === 4) {
128 | alphaFromHex = Number.parseInt(hex.slice(3, 4).repeat(2), 16) / 255;
129 | hex = hex.slice(0, 3);
130 | }
131 |
132 | if (hex.length === 3) {
133 | hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
134 | }
135 |
136 | const number = Number.parseInt(hex, 16);
137 | const red = number >> 16;
138 | const green = (number >> 8) & 255;
139 | const blue = number & 255;
140 | const alpha = typeof options.alpha === 'number' ? options.alpha : alphaFromHex;
141 |
142 | if (options.format === 'array') {
143 | return [red, green, blue, alpha];
144 | }
145 |
146 | if (options.format === 'css') {
147 | const alphaString = alpha === 1 ? '' : ` / ${Number((alpha * 100).toFixed(2))}%`;
148 | return `rgb(${red} ${green} ${blue}${alphaString})`;
149 | }
150 |
151 | return {red, green, blue, alpha};
152 | }
153 | // #endregion
154 |
155 |
156 | // #region colorNames
157 | export const colorName = {
158 | aliceblue: [240, 248, 255],
159 | antiquewhite: [250, 235, 215],
160 | aqua: [0, 255, 255],
161 | aquamarine: [127, 255, 212],
162 | azure: [240, 255, 255],
163 | beige: [245, 245, 220],
164 | bisque: [255, 228, 196],
165 | black: [0, 0, 0],
166 | blanchedalmond: [255, 235, 205],
167 | blue: [0, 0, 255],
168 | blueviolet: [138, 43, 226],
169 | brown: [165, 42, 42],
170 | burlywood: [222, 184, 135],
171 | cadetblue: [95, 158, 160],
172 | chartreuse: [127, 255, 0],
173 | chocolate: [210, 105, 30],
174 | coral: [255, 127, 80],
175 | cornflowerblue: [100, 149, 237],
176 | cornsilk: [255, 248, 220],
177 | crimson: [220, 20, 60],
178 | cyan: [0, 255, 255],
179 | darkblue: [0, 0, 139],
180 | darkcyan: [0, 139, 139],
181 | darkgoldenrod: [184, 134, 11],
182 | darkgray: [169, 169, 169],
183 | darkgreen: [0, 100, 0],
184 | darkgrey: [169, 169, 169],
185 | darkkhaki: [189, 183, 107],
186 | darkmagenta: [139, 0, 139],
187 | darkolivegreen: [85, 107, 47],
188 | darkorange: [255, 140, 0],
189 | darkorchid: [153, 50, 204],
190 | darkred: [139, 0, 0],
191 | darksalmon: [233, 150, 122],
192 | darkseagreen: [143, 188, 143],
193 | darkslateblue: [72, 61, 139],
194 | darkslategray: [47, 79, 79],
195 | darkslategrey: [47, 79, 79],
196 | darkturquoise: [0, 206, 209],
197 | darkviolet: [148, 0, 211],
198 | deeppink: [255, 20, 147],
199 | deepskyblue: [0, 191, 255],
200 | dimgray: [105, 105, 105],
201 | dimgrey: [105, 105, 105],
202 | dodgerblue: [30, 144, 255],
203 | firebrick: [178, 34, 34],
204 | floralwhite: [255, 250, 240],
205 | forestgreen: [34, 139, 34],
206 | fuchsia: [255, 0, 255],
207 | gainsboro: [220, 220, 220],
208 | ghostwhite: [248, 248, 255],
209 | gold: [255, 215, 0],
210 | goldenrod: [218, 165, 32],
211 | gray: [128, 128, 128],
212 | green: [0, 128, 0],
213 | greenyellow: [173, 255, 47],
214 | grey: [128, 128, 128],
215 | honeydew: [240, 255, 240],
216 | hotpink: [255, 105, 180],
217 | indianred: [205, 92, 92],
218 | indigo: [75, 0, 130],
219 | ivory: [255, 255, 240],
220 | khaki: [240, 230, 140],
221 | lavender: [230, 230, 250],
222 | lavenderblush: [255, 240, 245],
223 | lawngreen: [124, 252, 0],
224 | lemonchiffon: [255, 250, 205],
225 | lightblue: [173, 216, 230],
226 | lightcoral: [240, 128, 128],
227 | lightcyan: [224, 255, 255],
228 | lightgoldenrodyellow: [250, 250, 210],
229 | lightgray: [211, 211, 211],
230 | lightgreen: [144, 238, 144],
231 | lightgrey: [211, 211, 211],
232 | lightpink: [255, 182, 193],
233 | lightsalmon: [255, 160, 122],
234 | lightseagreen: [32, 178, 170],
235 | lightskyblue: [135, 206, 250],
236 | lightslategray: [119, 136, 153],
237 | lightslategrey: [119, 136, 153],
238 | lightsteelblue: [176, 196, 222],
239 | lightyellow: [255, 255, 224],
240 | lime: [0, 255, 0],
241 | limegreen: [50, 205, 50],
242 | linen: [250, 240, 230],
243 | magenta: [255, 0, 255],
244 | maroon: [128, 0, 0],
245 | mediumaquamarine: [102, 205, 170],
246 | mediumblue: [0, 0, 205],
247 | mediumorchid: [186, 85, 211],
248 | mediumpurple: [147, 112, 219],
249 | mediumseagreen: [60, 179, 113],
250 | mediumslateblue: [123, 104, 238],
251 | mediumspringgreen: [0, 250, 154],
252 | mediumturquoise: [72, 209, 204],
253 | mediumvioletred: [199, 21, 133],
254 | midnightblue: [25, 25, 112],
255 | mintcream: [245, 255, 250],
256 | mistyrose: [255, 228, 225],
257 | moccasin: [255, 228, 181],
258 | navajowhite: [255, 222, 173],
259 | navy: [0, 0, 128],
260 | oldlace: [253, 245, 230],
261 | olive: [128, 128, 0],
262 | olivedrab: [107, 142, 35],
263 | orange: [255, 165, 0],
264 | orangered: [255, 69, 0],
265 | orchid: [218, 112, 214],
266 | palegoldenrod: [238, 232, 170],
267 | palegreen: [152, 251, 152],
268 | paleturquoise: [175, 238, 238],
269 | palevioletred: [219, 112, 147],
270 | papayawhip: [255, 239, 213],
271 | peachpuff: [255, 218, 185],
272 | peru: [205, 133, 63],
273 | pink: [255, 192, 203],
274 | plum: [221, 160, 221],
275 | powderblue: [176, 224, 230],
276 | purple: [128, 0, 128],
277 | rebeccapurple: [102, 51, 153],
278 | red: [255, 0, 0],
279 | rosybrown: [188, 143, 143],
280 | royalblue: [65, 105, 225],
281 | saddlebrown: [139, 69, 19],
282 | salmon: [250, 128, 114],
283 | sandybrown: [244, 164, 96],
284 | seagreen: [46, 139, 87],
285 | seashell: [255, 245, 238],
286 | sienna: [160, 82, 45],
287 | silver: [192, 192, 192],
288 | skyblue: [135, 206, 235],
289 | slateblue: [106, 90, 205],
290 | slategray: [112, 128, 144],
291 | slategrey: [112, 128, 144],
292 | snow: [255, 250, 250],
293 | springgreen: [0, 255, 127],
294 | steelblue: [70, 130, 180],
295 | tan: [210, 180, 140],
296 | teal: [0, 128, 128],
297 | thistle: [216, 191, 216],
298 | tomato: [255, 99, 71],
299 | turquoise: [64, 224, 208],
300 | violet: [238, 130, 238],
301 | wheat: [245, 222, 179],
302 | white: [255, 255, 255],
303 | whitesmoke: [245, 245, 245],
304 | yellow: [255, 255, 0],
305 | yellowgreen: [154, 205, 50]
306 | }
307 | // #endregion
308 |
309 |
310 | export const parseCSSColor = (str, debug=false) => {
311 | if (typeof str !== 'string') {
312 | console.error(`parseCSSColor: expected a string found ${typeof str}`,str);
313 | return null;
314 | }
315 |
316 | const hex = hex_pattern.exec(str);
317 | if (hex) {
318 | if (debug){
319 | console.debug('parseCSSColor: hex', hex);
320 | }
321 | return getHEX(hex[0]);
322 | }
323 |
324 | const hsl = hsl4_pattern.exec(str) || hsl3_pattern.exec(str);
325 | if (hsl) {
326 | if (debug){
327 | console.debug('parseCSSColor: hsl', hsl);
328 | }
329 | return getHSL(hsl);
330 | }
331 |
332 | const rgb =
333 | rgb4_pattern.exec(str) ||
334 | rgb3_pattern.exec(str)
335 | if (rgb) {
336 | if (debug){
337 | console.debug('parseCSSColor: rgb', rgb);
338 | }
339 | return getRGB(rgb);
340 | }
341 |
342 | if (transparent_pattern.exec(str)) {
343 | if (debug){
344 | console.debug('parseCSSColor: transparent');
345 | }
346 | return getRGB([null, 0, 0, 0, 0]);
347 | }
348 |
349 | const cn = colorName[str.toLowerCase()];
350 | if (cn) {
351 | if (debug){
352 | console.debug('parseCSSColor: colorName', cn);
353 | }
354 | return getRGB([null, cn[0], cn[1], cn[2], 1]);
355 | }
356 |
357 | console.error('parseCSSColor: unknown color', str);
358 | return null;
359 | };
360 |
361 | export default parseCSSColor;
362 |
363 |
--------------------------------------------------------------------------------