Compare commits

..
34 Commits
Author SHA1 Message Date
THE_BEAST\me 30246eb831 chore: Update version to 1.13.5 and enhance project description in metadata 2026-01-14 20:52:41 -05:00
THE_BEAST\me c97c290dba feat: Add fallback video metadata extraction using ffprobe in API 2026-01-14 20:39:25 -05:00
THE_BEAST\me 2da9b2813b enhance JSON metadata extraction to use relative paths for caching 2026-01-14 20:01:53 -05:00
THE_BEAST\me aadb396151 Enhance PNG workflow metadata check to include A1111 parameters in clean up script 2026-01-14 19:47:25 -05:00
THE_BEAST\me 96c9248135 feat: Enhance A1111 parameters parsing and metadata extraction in prompt extractor 2026-01-14 19:27:25 -05:00
THE_BEAST\me 695d7421d4 enhance workflow indicator updates for various file types 2026-01-14 18:54:11 -05:00
THE_BEAST\me 9d8137281e feat: Add file organization script to manage files by workflow presence 2026-01-14 17:55:41 -05:00
THE_BEAST\me 546b2f697b enhance image preview loading logic to prevent unnecessary reloads 2026-01-14 17:24:59 -05:00
THE_BEAST\me 2d262999a3 feat: Release version 1.13.0 with new features and improvements
- Added a file browser modal with thumbnail previews in the Extractor, enhancing user experience for file selection.
- Implemented a caching system for thumbnails to improve loading speed.
- Updated version number to 1.13.0 in __init__.py and pyproject.toml.
- Enhanced file handling in the backend to support subfolder navigation and improved metadata caching.
- Added functionality to clear and manage cached video thumbnails.
- Improved state management in PromptManagerAdvanced to handle cases where input LoRAs are cleared.
2026-01-14 14:53:44 -05:00
THE_BEAST\me e36d0fb15f enhance reset functionality by tracking state changes and storing original strengths for LoRA adjustments 2026-01-14 12:13:31 -05:00
THE_BEAST\me d92a6c1872 enhance LoRA path handling by normalizing path separators and refactoring extension stripping logic 2026-01-14 11:27:10 -05:00
THE_BEAST\me 67df4c6e53 enhance LoRA extraction logic to only include connected nodes and add tests for disconnected LoRAs 2026-01-13 20:56:25 -05:00
THE_BEAST\me e08d18c783 bump version to 1.12.7; add reset functionality for LoRA strengths and improve user experience with live adjustments 2026-01-13 15:23:17 -05:00
THE_BEAST\me 769d40f9f5 enhance LoRA management by tracking input changes and improving display of unavailable LoRAs 2026-01-13 14:15:01 -05:00
THE_BEAST\me eef07948ac enhance video frame extraction and caching mechanism in PromptExtractor 2026-01-13 00:31:49 -05:00
THE_BEAST\me bf847e9639 chore: update version to 1.12.6 and enhance caching behavior in prompt extractor and prompt manager advanced 2026-01-12 23:06:27 -05:00
THE_BEAST\me 39c8b5f3b8 enhance video frame caching functionality 2026-01-12 20:01:40 -05:00
THE_BEAST\me cf810ca921 Updated Readme 2026-01-12 18:51:33 -05:00
THE_BEAST\me 422607ec8d Refactor prompt extraction and enhance LoRA matching
- Removed unnecessary print statements from prompt_extractor.py to clean up logging.
- Simplified LoRA stack processing by directly using paths if available.
- Introduced fuzzy matching for LoRA names in prompt_manager_advanced.py to handle renamed LoRAs.
- Added a new test suite (test_fuzzy_match.py) to validate fuzzy matching logic with various scenarios.
2026-01-12 18:43:17 -05:00
THE_BEAST\me f9e26c8bbd Added Lora Stack Input to Extractor.
Enhance LoRA and Prompt extraction logic, added tests
2026-01-12 17:15:22 -05:00
THE_BEAST\me be52d65de9 chore: add better drag-and-drop file upload support in Prompt Extractor 2026-01-12 00:37:23 -05:00
THE_BEAST\me 1d6021a916 chore: Bump version to 1.11.4 in __init__.py, pyproject.toml, and update changelog 2026-01-11 17:26:57 -05:00
THE_BEAST\me 6f0ac2674b chore: added workflow metadata notification in prompt extractor 2026-01-11 17:14:15 -05:00
THE_BEAST\me 6ba1f3f346 Update: Improved Prompt Extractor caching of metadata from images, videos, and JSON files. Removed need for ffmpeg and more consistent with how Comfy does it. 2026-01-11 16:26:44 -05:00
THE_BEAST\me 27ab751796 feat: Update Prompt Extractor to support video file extraction and enhance file listing API
chore: Bump version to 1.11.2 in __init__.py and pyproject.toml
docs: Improve README with detailed descriptions for Prompt Extractor and its functionalities
2026-01-11 12:43:53 -05:00
THE_BEAST\me e2a9b25978 chore: Bump version to 1.11.1 in __init__.py and pyproject.toml 2026-01-11 01:26:38 -05:00
THE_BEAST\me 9b8016821c docs: Update README to clarify Prompt Manager features and enhance Prompt Extractor description 2026-01-11 01:24:42 -05:00
THE_BEAST\me 4811f21255 Adjusted how Loras are seved 2026-01-11 01:11:33 -05:00
THE_BEAST\me ca645721ec feat: Enhance prompt management with thumbnail support and image processing
- Added functionality to save and retrieve thumbnails for prompts in 'prompt_manager_advanced.py`.
- Implemented image processing to convert image tensors to base64 thumbnails.
- Updated prompt saving logic to include thumbnail data.
- Introduced new API endpoint to save or remove thumbnails for prompts.
- Improved handling of LoRA paths and trigger words, ensuring case-insensitivity and better user experience.
- added a Prompt Extractor that analyses any valid input and extract Prompt and Loras
- Updated version to 1.11.0 in `pyproject.toml`.
2026-01-11 00:45:22 -05:00
THE_BEAST\me 457e137b4c Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2026-01-09 17:02:35 -05:00
THE_BEAST\me 603c34d601 feat: Enhance Prompt Manager with input validation, import functionality and trigger word support.
- Added VALIDATE_INPUTS method to allow temporary unsaved prompts in PromptManager and PromptManagerAdvanced.
- Updated save_prompt and save_prompt_advanced to require only category and name, allowing empty text for unsaved prompts.
- Implemented import and export functionality for prompts in both PromptManager and PromptManagerAdvanced, supporting merge and replace modes.
- Enhanced prompt data structure to include trigger words, with appropriate handling in save and retrieval methods.
- Updated version to 1.10.0 in pyproject.toml.
2026-01-09 17:00:11 -05:00
Francois Beaudry 4fae27a6dd Add GNU General Public License v3 2026-01-09 12:02:07 -05:00
Francois Beaudry 55a2fd64c9 Revise README for prompt manager enhancements
Updated README to reflect new features and compatibility.
2026-01-09 11:28:25 -05:00
Francois Beaudry 5450682d44 Update README with Lora Manager compatibility
Added compatibility information for Lora Manager.
2026-01-09 11:27:17 -05:00
19 changed files with 9686 additions and 497 deletions
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+105 -18
View File
@@ -1,34 +1,33 @@
# ComfyUI Prompt Manager
## A custom [ComfyUI](https://github.com/comfyanonymous/ComfyUI) node for Organizing, Generating or Enhancing prompts.
## A comprehensive prompt toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, and Extract prompts with full LoRA support.
This addon started off as a simple prompt Manager, to help save and retrieve prompts.
But has since evolved to allow generating prompts for Images, video and Image analysis.
The new advanced version of the manager, now allows the user to save the entire recipe,
as it allows saving the Lora Stacks that goes with a prompt. Supporting Dual Stack for Wan.
A complete prompt management solution featuring three core capabilities:
**Prompt Manager** — Save and organize prompts with categories, simple UI with minimal feature.
**Prompt Manager Advanced** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Will also remap Loras if path differs.
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp). Supports text enhancement, image analysis with vision models (Qwen3VL), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
**Prompt Extractor** — Extract prompts and LoRA configurations from existing images, videos, or JSON workflow files. Will extract first frame from any video. Automatically parses embedded metadata and outputs active LoRA as Lora stacks. When used in conjunction with Prompt Manager Advanced, Loras will be automatically found if available, regardless of path. For those that aren't, right click offers the option to look for them on Civitai.
___
For Prompt Generation, it uses an existing install of [llama.cpp](https://github.com/ggerganov/llama.cpp), preventing install conflicts with ComfyUI.
Provides options to automatically download Qwen3 and Qwen3VL models.
Supports prompt enhancing, image analysis, or custom image processing, with up to 5 images at once.
Custom GGUF models can be used if supported by llama.cpp; simply drop them in the models/gguf folder.
Users can now set a custom Llama-server path as well as a custom Model Path in ComfyUI's preferences.
If a Custom Model Path is added, it will become the default download folder.
<div align="center">
<figcaption>Simple Prompt Generator Usage</figcaption>
<img src="docs/prompt_manager.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Advanced Prompt Generator Usage</figcaption>
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Prompt Manager Advanced, with Lora support</figcaption>
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
</div>
### Key features:
### Prompt Manager:
@@ -39,22 +38,34 @@ If a Custom Model Path is added, it will become the default download folder.
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
### Prompt Manager Advanced:
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA integration
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and Trigger word integration
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs, can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
- **LoRA Manager Integration**: If [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) is installed, hovering over LoRA tags shows preview images
- **Missing LoRA Detection**: LoRAs that aren't found on your system are highlighted in red
### Apply LoRA Stack:
### Prompt Apply LoRA:
- **Simple LoRA Application**: Takes a LORA_STACK and applies it to your model/clip
- **Works with Any Stacker**: Compatible with LoRA Manager's stacker or any node outputting LORA_STACK
- **Optional CLIP**: CLIP input is optional for workflows that don't need it
### Prompt Extractor:
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
- **Dual LoRA Stack Output**: Outputs two separate LoRA stacks for workflows using dual stacking (e.g., Wan video)
- **Active LoRA Filtering**: Only extracts LoRAs that are marked as active in the source workflow
- **Wide Node Compatibility**: Supports extraction from CLIP Text Encode, various sampler nodes, and LoRA stackers including Power Lora Loader
- **Preview in Manager**: View extracted data and repathed loras using Manager Advanced.
### Prompt Generator
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
@@ -135,6 +146,14 @@ If a Custom Model Path is added, it will become the default download folder.
4. **Optional CLIP**: Connect CLIP if your workflow needs it (some video workflows don't)
5. **Use Outputs**: Connect the modified model/clip to your sampler or other nodes
### Prompt Extractor
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
2. **Load Media**: Select an image or video from your input folder or use the upload button to access file from anywhere.
3. **JSON Workflows**: Support extracting from JSON, by importing workflow files directly using the upload button.
4. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
5. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
6. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
### Prompt Generator
@@ -223,6 +242,74 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
## Changelog
### version 1.13.5
- Added browse window with thumbnails in Extractor, with cache system for speedup.
- Bug fix for issue caused by new additions.
### version 1.12.7
- Quality of life improvements and added option to change the Strenght of any Lora in Manager, so we can tweak Extracted Workflows Live.
### version 1.12.6
- Tweak to caching behavior for prompt extractor and prompt manager advanced
### version 1.12.5
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
### version 1.12.0
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
- Prompt Extractor: Improved logic for determining Positive prompts in Worfklow.
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
### Version 1.11.5
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
### Version 1.11.2
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
### Version 1.11.0
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
- Browse and load JSON workflow files directly
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
- Filters inactive LoRAs - only extracts LoRAs marked as active
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
- Visual identification of prompts in the dropdown selector
- Thumbnails stored alongside prompt data for easy management
- **Simplified "New Prompt" button**
- Now clears fields immediately without asking for a name
- Enter the name when saving instead of when creating
- Keeps you in the current category for faster workflow
- **Bug fixes and improvements**
- Fixed JSON workflow file path resolution
- Improved LoRA extraction for complex workflows
### Version 1.10.0
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
- Save Prompt opens a modal with category selection (create new or select existing)
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
- **Import/Export JSON functionality**
- Export all prompts to a JSON file
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
- Proper cancel handling without false success messages
- **Multi-tab synchronization**
- Changing category or prompt reloads data from server
- Prevents conflicts when editing prompts in multiple browser tabs
- **Prompt Manager now preserves LoRA data**
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
- **Trigger Words support in Prompt Manager Advanced**
- Save and restore trigger words alongside prompts and LoRAs
- Trigger words display as editable text when loading saved prompts
- **Improved unsaved changes detection**
- Warning when switching away from newly created (unsaved) prompts
- Cancel button properly reverts dropdown to previous selection
### Version 1.9.0
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
+7 -4
View File
@@ -2,7 +2,7 @@
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
A prompt management system for ComfyUI with LLM input support
"""
__version__ = "1.9.1"
__version__ = "1.13.5"
__author__ = "François Beaudry"
__license__ = "MIT"
@@ -10,7 +10,8 @@ from .prompt_manager import PromptManager
from .prompt_manager_advanced import PromptManagerAdvanced
from .prompt_generator import PromptGenerator
from .prompt_generator_options import PromptGenOptions
from .apply_lora_stack import ApplyLoRAStack
from .prompt_apply_lora import PromptApplyLora
from .prompt_extractor import PromptExtractor
from .model_manager import get_local_models
from server import PromptServer
@@ -19,7 +20,8 @@ NODE_CLASS_MAPPINGS = {
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"ApplyLoRAStack": ApplyLoRAStack
"PromptApplyLora": PromptApplyLora,
"PromptExtractor": PromptExtractor
}
NODE_DISPLAY_NAME_MAPPINGS = {
@@ -27,7 +29,8 @@ NODE_DISPLAY_NAME_MAPPINGS = {
"PromptManagerAdvanced": "Prompt Manager Advanced",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"ApplyLoRAStack": "Apply LoRA Stack"
"PromptApplyLora": "Prompt Apply LoRA",
"PromptExtractor": "Prompt Extractor"
}
WEB_DIRECTORY = "./js"
Binary file not shown.

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 120 KiB

+710
View File
@@ -0,0 +1,710 @@
/**
* File Browser Modal for PromptExtractor
* Shows thumbnails of files in input directory
*/
// Track current subfolder for navigation
let currentSubfolder = '';
export function createFileBrowserModal(currentFile, onFileSelect) {
// Reset to root on open
currentSubfolder = '';
// Create modal overlay
const overlay = document.createElement('div');
overlay.className = 'prompt-extractor-browser-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
`;
// Create modal container (match PromptManagerAdvanced styling)
const modal = document.createElement('div');
modal.className = 'prompt-extractor-browser-modal';
modal.style.cssText = `
background: rgba(40, 44, 52, 0.98);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 6px;
width: 90%;
max-width: 1200px;
height: 80%;
max-height: 800px;
display: flex;
flex-direction: column;
overflow: hidden;
`;
// Create header
const header = document.createElement('div');
header.style.cssText = `
padding: 15px 20px;
border-bottom: 1px solid rgba(255,255,255,0.1);
display: flex;
flex-direction: column;
gap: 8px;
`;
const topRow = document.createElement('div');
topRow.style.cssText = 'display: flex; justify-content: space-between; align-items: center;';
topRow.innerHTML = `
<h3 style="margin: 0; color: #aaa;">Select File from Input Folder</h3>
<div style="display: flex; gap: 10px; align-items: center;">
<button class="regenerate-cache-btn" style="
background: #333;
border: 1px solid #555;
border-radius: 6px;
color: #ccc;
padding: 5px 12px;
cursor: pointer;
font-size: 12px;
">Regenerate Cache</button>
<button class="close-btn" style="
background: none;
border: none;
color: #aaa;
font-size: 24px;
cursor: pointer;
padding: 0;
width: 30px;
height: 30px;
">×</button>
</div>
`;
const breadcrumb = document.createElement('div');
breadcrumb.className = 'folder-breadcrumb';
breadcrumb.style.cssText = 'font-size: 12px; color: #888; cursor: pointer;';
breadcrumb.textContent = 'input/';
breadcrumb.onclick = () => {
if (currentSubfolder) {
currentSubfolder = '';
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
}
};
header.appendChild(topRow);
header.appendChild(breadcrumb);
// Create search/filter bar
const filterBar = document.createElement('div');
filterBar.style.cssText = `
padding: 10px 20px;
border-bottom: 1px solid rgba(255,255,255,0.1);
display: flex;
gap: 10px;
`;
filterBar.innerHTML = `
<input type="text" placeholder="Search files..." class="search-input" style="
flex: 1;
padding: 8px 12px;
background: rgba(45, 55, 72, 0.7);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 6px;
color: #ccc;
">
<select class="filter-type" style="
padding: 8px 12px;
background: rgba(45, 55, 72, 0.7);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 6px;
color: #ccc;
">
<option value="all">All Files</option>
<option value="image">Images</option>
<option value="video">Videos</option>
<option value="json">JSON</option>
</select>
`;
// Create thumbnail grid container
const gridContainer = document.createElement('div');
gridContainer.className = 'thumbnail-grid';
gridContainer.style.cssText = `
flex: 1;
overflow-y: auto;
padding: 20px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 15px;
align-content: start;
`;
// Create loading indicator
const loading = document.createElement('div');
loading.style.cssText = `
text-align: center;
padding: 40px;
color: #aaa;
`;
loading.textContent = 'Loading files...';
gridContainer.appendChild(loading);
// Assemble modal
modal.appendChild(header);
modal.appendChild(filterBar);
modal.appendChild(gridContainer);
overlay.appendChild(modal);
// Close button handler
const closeBtn = topRow.querySelector('.close-btn');
closeBtn.onclick = () => document.body.removeChild(overlay);
overlay.onclick = (e) => {
if (e.target === overlay) document.body.removeChild(overlay);
};
// Regenerate cache button handler
const regenerateCacheBtn = topRow.querySelector('.regenerate-cache-btn');
regenerateCacheBtn.onclick = () => {
clearThumbnailCache();
// Reload thumbnails to regenerate them
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
};
// Add to DOM
document.body.appendChild(overlay);
// Load files
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
// Setup search/filter
const searchInput = filterBar.querySelector('.search-input');
const filterType = filterBar.querySelector('.filter-type');
searchInput.oninput = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
filterType.onchange = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
}
async function loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
try {
// Update breadcrumb
if (!currentSubfolder) {
breadcrumbElement.textContent = 'input/';
} else {
breadcrumbElement.textContent = `input/${currentSubfolder}/`;
}
// Fetch file list from server
const response = await fetch('/prompt-extractor/list-files');
const data = await response.json();
container.innerHTML = '';
if (!data.files || data.files.length === 0) {
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #aaa;">No files found in input directory</div>';
return;
}
// Get all files with their full paths
const allFiles = data.files.filter(f => f !== '(none)');
// Filter files/folders for current directory
const currentFiles = [];
const subfolders = new Set();
const prefix = currentSubfolder ? currentSubfolder + '/' : '';
allFiles.forEach(filepath => {
if (filepath.startsWith(prefix)) {
const remainder = filepath.substring(prefix.length);
const slashIndex = remainder.indexOf('/');
if (slashIndex === -1) {
// It's a file in current directory
currentFiles.push(filepath);
} else {
// It's in a subdirectory - extract folder name
const folderName = remainder.substring(0, slashIndex);
subfolders.add(folderName);
}
}
});
// Add "back" button if in subfolder
if (currentSubfolder) {
const backItem = createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement);
container.appendChild(backItem);
}
// Add folder items
Array.from(subfolders).sort().forEach(folderName => {
const folderItem = createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement);
container.appendChild(folderItem);
});
// Create thumbnail for each file
currentFiles.forEach(filename => {
const item = createThumbnailItem(filename, currentFile, onFileSelect, overlay);
container.appendChild(item);
});
} catch (error) {
console.error('[FileBrowser] Error loading files:', error);
container.innerHTML = '<div style="text-align: center; padding: 40px; color: rgba(220, 53, 69, 0.9);">Error loading files</div>';
}
}
function createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
const item = document.createElement('div');
item.className = 'folder-item';
item.style.cssText = `
background: rgba(45, 55, 72, 0.7);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 6px;
padding: 8px;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 8px;
`;
const preview = document.createElement('div');
preview.style.cssText = `
width: 100%;
height: 150px;
background: rgba(0, 0, 0, 0.5);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
font-size: 64px;
`;
preview.textContent = '←';
const label = document.createElement('div');
label.textContent = 'Back';
label.style.cssText = `
font-size: 12px;
color: #ccc;
text-align: center;
`;
item.appendChild(preview);
item.appendChild(label);
item.onmouseenter = () => {
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
item.style.transform = 'translateY(-2px)';
item.style.background = 'rgba(50, 112, 163, 0.5)';
};
item.onmouseleave = () => {
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
item.style.transform = 'translateY(0)';
item.style.background = 'rgba(45, 55, 72, 0.7)';
};
item.onclick = () => {
// Go up one level
const parts = currentSubfolder.split('/');
parts.pop();
currentSubfolder = parts.join('/');
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
};
return item;
}
function createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement) {
const item = document.createElement('div');
item.className = 'folder-item';
item.style.cssText = `
background: rgba(45, 55, 72, 0.7);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 6px;
padding: 8px;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 8px;
`;
const preview = document.createElement('div');
preview.style.cssText = `
width: 100%;
height: 150px;
background: rgba(0, 0, 0, 0.5);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
font-size: 64px;
`;
preview.textContent = '📁';
const label = document.createElement('div');
label.textContent = folderName;
label.style.cssText = `
font-size: 12px;
color: #ccc;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
`;
label.title = folderName;
item.appendChild(preview);
item.appendChild(label);
item.onmouseenter = () => {
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
item.style.transform = 'translateY(-2px)';
item.style.background = 'rgba(50, 112, 163, 0.5)';
};
item.onmouseleave = () => {
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
item.style.transform = 'translateY(0)';
item.style.background = 'rgba(45, 55, 72, 0.7)';
};
item.onclick = () => {
// Navigate into folder
currentSubfolder = currentSubfolder ? `${currentSubfolder}/${folderName}` : folderName;
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
};
return item;
}
function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
const item = document.createElement('div');
item.className = 'thumbnail-item';
item.dataset.filename = filename;
item.dataset.type = getFileType(filename);
const isSelected = filename === currentFile;
item.style.cssText = `
background: rgba(45, 55, 72, 0.7);
border: 1px solid ${isSelected ? 'rgba(66, 153, 225, 0.9)' : 'rgba(226, 232, 240, 0.2)'};
border-radius: 6px;
padding: 8px;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 8px;
`;
// Thumbnail preview
const preview = document.createElement('div');
preview.style.cssText = `
width: 100%;
height: 150px;
background: rgba(0, 0, 0, 0.5);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
`;
const ext = filename.split('.').pop().toLowerCase();
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
if (imageExts.includes(ext)) {
const img = document.createElement('img');
// Handle subfolder paths: split filename into folder and basename
let subfolder = '';
let basename = filename;
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
basename = filename.substring(lastSlash + 1);
}
img.src = `/view?filename=${encodeURIComponent(basename)}&type=input&subfolder=${encodeURIComponent(subfolder)}`;
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
img.onerror = () => {
// Use placeholder image
img.src = new URL("./placeholder.png", import.meta.url).href;
};
preview.appendChild(img);
} else if (videoExts.includes(ext)) {
// Extract video thumbnail with caching
extractVideoThumbnailCached(filename, preview);
} else if (ext === 'json') {
// Use placeholder for JSON
const img = document.createElement('img');
img.src = new URL("./placeholder.png", import.meta.url).href;
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
preview.appendChild(img);
} else {
// Use placeholder for unknown types
const img = document.createElement('img');
img.src = new URL("./placeholder.png", import.meta.url).href;
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
preview.appendChild(img);
}
// Filename label (show only basename, not full path)
const label = document.createElement('div');
const basename = filename.includes('/') ? filename.split('/').pop() : filename;
label.textContent = basename;
label.style.cssText = `
font-size: 12px;
color: ${isSelected ? '#fff' : '#ccc'};
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
`;
label.title = filename; // Full path in tooltip
item.appendChild(preview);
item.appendChild(label);
// Hover effect
item.onmouseenter = () => {
if (!isSelected) {
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
item.style.transform = 'translateY(-2px)';
item.style.background = 'rgba(50, 112, 163, 0.5)';
}
};
item.onmouseleave = () => {
if (!isSelected) {
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
item.style.transform = 'translateY(0)';
item.style.background = 'rgba(45, 55, 72, 0.7)';
}
};
// Click handler
item.onclick = () => {
onFileSelect(filename);
document.body.removeChild(overlay);
};
return item;
}
function getFileType(filename) {
const ext = filename.split('.').pop().toLowerCase();
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
if (imageExts.includes(ext)) return 'image';
if (videoExts.includes(ext)) return 'video';
if (ext === 'json') return 'json';
return 'other';
}
function filterThumbnails(container, searchText, fileType) {
const items = container.querySelectorAll('.thumbnail-item');
const search = searchText.toLowerCase();
items.forEach(item => {
const filename = item.dataset.filename.toLowerCase();
const type = item.dataset.type;
const matchesSearch = !searchText || filename.includes(search);
const matchesType = fileType === 'all' || type === fileType;
item.style.display = (matchesSearch && matchesType) ? 'flex' : 'none';
});
}
/**
* Extract thumbnail from video file with caching
* Caches thumbnails in browser's localStorage
*/
async function extractVideoThumbnailCached(filename, previewElement) {
// Use full path as cache key to avoid conflicts between subfolders
const cacheKey = `video_thumb_${filename.replace(/[\/\\]/g, '_')}`;
try {
// Check if we have a cached thumbnail
const cachedThumb = localStorage.getItem(cacheKey);
// If cache exists, use it (trust localStorage until manual regeneration)
if (cachedThumb) {
const img = document.createElement('img');
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
img.src = cachedThumb;
previewElement.innerHTML = '';
previewElement.appendChild(img);
return;
}
} catch (error) {
console.log('[FileBrowser] Cache check failed, generating new thumbnail:', error);
}
// No cache, extract new thumbnail
extractVideoThumbnail(filename, previewElement, cacheKey);
}
/**
* Extract thumbnail from video file
* Fast, lightweight version for preview purposes only
*/
async function extractVideoThumbnail(filename, previewElement, cacheKey = null) {
// Show placeholder while loading
const placeholderImg = document.createElement('img');
placeholderImg.src = new URL("./placeholder.png", import.meta.url).href;
placeholderImg.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
previewElement.innerHTML = '';
previewElement.appendChild(placeholderImg);
// Create video element with minimal settings for fast loading
const video = document.createElement('video');
video.crossOrigin = 'anonymous';
video.preload = 'metadata';
video.muted = true;
video.playsInline = true;
video.style.display = 'none';
video.onloadedmetadata = () => {
// Use absolute first frame (no seeking = fastest)
video.currentTime = 0;
};
video.onseeked = async () => {
try {
// Create small canvas for fast rendering (thumbnail size)
const maxWidth = 180;
const maxHeight = 150;
const aspectRatio = video.videoWidth / video.videoHeight;
let width, height;
if (aspectRatio > maxWidth / maxHeight) {
width = maxWidth;
height = maxWidth / aspectRatio;
} else {
height = maxHeight;
width = maxHeight * aspectRatio;
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { alpha: false });
// Draw video frame to small canvas
ctx.drawImage(video, 0, 0, width, height);
// Create image from canvas with lower quality for speed
const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
const img = document.createElement('img');
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
img.src = dataUrl;
// Replace placeholder with thumbnail (display first, cache later)
previewElement.innerHTML = '';
previewElement.appendChild(img);
// Cache the thumbnail asynchronously after display (non-blocking)
if (cacheKey) {
setTimeout(() => {
try {
localStorage.setItem(cacheKey, dataUrl);
console.log(`[FileBrowser] Cached thumbnail for: ${filename}`);
} catch (cacheError) {
console.log('[FileBrowser] Failed to cache thumbnail:', cacheError);
}
}, 0);
}
// Clean up
video.remove();
} catch (error) {
console.error('[FileBrowser] Error extracting video thumbnail:', error);
// Keep placeholder on error
video.remove();
}
};
video.onerror = () => {
console.error('[FileBrowser] Error loading video for thumbnail:', filename);
// Keep placeholder on error
video.remove();
};
// Load video from input directory
// Handle subfolder paths: split filename into folder and basename
let subfolder = '';
let basename = filename;
if (filename.includes('/')) {
const lastSlash = filename.lastIndexOf('/');
subfolder = filename.substring(0, lastSlash);
basename = filename.substring(lastSlash + 1);
}
video.src = `/view?filename=${encodeURIComponent(basename)}&type=input&subfolder=${encodeURIComponent(subfolder)}&${Date.now()}`;
}
/**
* Clear all video thumbnail cache
*/
function clearThumbnailCache() {
try {
const cachePrefix = 'video_thumb_';
const keysToRemove = [];
// Find all cache keys in localStorage
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(cachePrefix)) {
keysToRemove.push(key);
}
}
// Remove all cache entries
keysToRemove.forEach(key => {
localStorage.removeItem(key);
});
console.log(`[FileBrowser] Cleared ${keysToRemove.length} cache entries`);
} catch (error) {
console.error('[FileBrowser] Error clearing cache:', error);
}
}
/**
* Clean up orphaned thumbnail cache entries
* Removes cache for files that no longer exist in the input directory
*/
function cleanupOrphanedThumbnailCache(currentFiles) {
try {
const cachePrefix = 'video_thumb_';
const timePrefix = 'video_thumb_time_';
const keysToRemove = [];
// Find all cache keys in localStorage
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
// Check if it's a video thumbnail cache key
if (key && key.startsWith(cachePrefix)) {
// Extract filename from cache key
const filename = key.substring(cachePrefix.length);
// If this filename is not in current files list, mark for removal
if (!currentFiles.includes(filename)) {
keysToRemove.push(key);
keysToRemove.push(timePrefix + filename);
}
}
}
// Remove orphaned cache entries
keysToRemove.forEach(key => {
localStorage.removeItem(key);
});
if (keysToRemove.length > 0) {
console.log(`[FileBrowser] Cleaned up ${keysToRemove.length / 2} orphaned thumbnail cache entries`);
}
} catch (error) {
console.error('[FileBrowser] Error cleaning up cache:', error);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 747 B

File diff suppressed because it is too large Load Diff
+658 -78
View File
@@ -220,14 +220,17 @@ app.registerExtension({
}
});
// Load prompts on creation
loadPrompts(node).then(() => {
addButtonBar(node);
setupCategoryChangeHandler(node);
filterPromptDropdown(node);
setupUseExternalToggleHandler(node);
// IMPORTANT: Add DOM widgets SYNCHRONOUSLY during node creation
// to ensure proper positioning and rendering within the node bounds
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
// After buttons are added, ensure height is sufficient
// Load prompts asynchronously (data only, not widgets)
loadPrompts(node).then(() => {
filterPromptDropdown(node);
// Ensure height is sufficient after data is loaded
setTimeout(() => {
const computedSize = node.computeSize();
const minHeight = Math.max(400, computedSize[1] + 20);
@@ -235,7 +238,8 @@ app.registerExtension({
if (node.size[1] < minHeight) {
node.setSize([Math.max(400, node.size[0]), minHeight]);
}
}, 200);
app.graph.setDirtyCanvas(true, true);
}, 100);
});
return result;
@@ -328,6 +332,39 @@ async function loadPrompts(node) {
}
}
/**
* Check if there are unsaved changes in the prompt
*/
function hasUnsavedChanges(node) {
// New unsaved prompt always has unsaved changes
if (node.isNewUnsavedPrompt) {
return true;
}
// For basic PromptManager, check if text differs from saved
const textWidget = node.widgets?.find(w => w.name === "text");
const categoryWidget = node.widgets?.find(w => w.name === "category");
const promptWidget = node.widgets?.find(w => w.name === "name");
if (!textWidget || !categoryWidget || !promptWidget) {
return false;
}
const currentText = textWidget.value || "";
const category = categoryWidget.value;
const promptName = promptWidget.value;
// If no saved prompt exists, no unsaved changes (unless it's a new prompt)
if (!node.prompts || !node.prompts[category] || !node.prompts[category][promptName]) {
return false;
}
const savedPrompt = node.prompts[category][promptName];
const savedText = savedPrompt?.prompt || "";
return currentText !== savedText;
}
function filterPromptDropdown(node) {
// Filter name dropdown to only show prompts from current category
const categoryWidget = node.widgets.find(w => w.name === "category");
@@ -354,96 +391,216 @@ function addButtonBar(node) {
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
// Create button container
// Create button container with proper styling for DOM widget
const buttonContainer = document.createElement("div");
buttonContainer.style.display = "flex";
buttonContainer.style.gap = "4px";
buttonContainer.style.padding = "2px 4px 4px 4px";
buttonContainer.style.flexWrap = "nowrap";
buttonContainer.style.marginTop = "-10px";
buttonContainer.style.width = "100%";
buttonContainer.style.boxSizing = "border-box";
buttonContainer.style.position = "relative";
// Create action buttons
const createCategoryBtn = createButton("New Category", async () => {
const categoryName = await showTextPrompt("New Category", "Enter new category name:");
// Save Prompt button with category selection
const savePromptBtn = createButton("Save Prompt", async () => {
const categories = Object.keys(node.prompts || {}).sort((a, b) => a.localeCompare(b));
const currentCategory = categoryWidget.value;
if (categoryName && categoryName.trim()) {
// Case-insensitive check for existing category - PREVENT overwriting
let existingCategoryName = null;
if (node.prompts) {
const existingCategories = Object.keys(node.prompts);
existingCategoryName = existingCategories.find(cat => cat.toLowerCase() === categoryName.trim().toLowerCase());
const result = await showPromptWithCategory(
"Save Prompt",
"Enter prompt name:",
promptWidget.value || "New Prompt",
categories,
currentCategory
);
if (result && result.name && result.name.trim()) {
const promptName = result.name.trim();
const targetCategory = result.category;
const promptText = textWidget.value;
if (!promptText || !promptText.trim()) {
await showInfo("Empty Prompt", "Prompt text cannot be empty");
return;
}
// Case-insensitive check for existing prompt
let existingPromptName = null;
if (node.prompts[targetCategory]) {
const existingNames = Object.keys(node.prompts[targetCategory]);
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
}
if (existingCategoryName) {
// Ask for confirmation before overwriting existing prompt
if (existingPromptName) {
const confirmed = await showConfirm(
"Overwrite Prompt",
`Prompt "${existingPromptName}" already exists in category "${targetCategory}". Do you want to overwrite it?`,
"Overwrite",
"#f80"
);
if (!confirmed) {
return;
}
}
await savePrompt(node, targetCategory, promptName, promptText.trim());
// Clear new prompt flag since it's now saved
node.isNewUnsavedPrompt = false;
node.newPromptCategory = null;
node.newPromptName = null;
// Update UI to show the saved prompt
categoryWidget.value = targetCategory;
filterPromptDropdown(node);
promptWidget.value = promptName;
}
});
// New Prompt button with category selection
const newPromptBtn = createButton("New Prompt", async () => {
// Check for unsaved changes before creating new prompt
const hasUnsaved = hasUnsavedChanges(node);
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges", true);
if (hasUnsaved && warnEnabled) {
const confirmed = await showConfirm(
"Unsaved Changes",
"You have unsaved changes to the current prompt. Do you want to discard them and create a new prompt?",
"Discard & Continue",
"#f80"
);
if (!confirmed) {
return;
}
}
const categories = Object.keys(node.prompts || {}).sort((a, b) => a.localeCompare(b));
const currentCategory = categoryWidget.value;
const result = await showPromptWithCategory(
"New Prompt",
"Enter new prompt name:",
"",
categories,
currentCategory
);
if (result && result.name && result.name.trim()) {
const promptName = result.name.trim();
const targetCategory = result.category;
// Check for existing prompt
let existingPromptName = null;
if (node.prompts[targetCategory]) {
const existingNames = Object.keys(node.prompts[targetCategory]);
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
}
if (existingPromptName) {
await showInfo(
"Category Exists",
`Category already exists as "${existingCategoryName}". Cannot overwrite existing categories.`
"Prompt Exists",
`Prompt "${existingPromptName}" already exists in category "${targetCategory}".`
);
return;
}
await createCategory(node, categoryName.trim());
// Set up UI for new prompt (temporary, not saved yet)
// User must click "Save Prompt" to persist it
categoryWidget.value = targetCategory;
// Add prompt name to dropdown temporarily so it can be selected
if (!promptWidget.options.values.includes(promptName)) {
promptWidget.options.values = [...promptWidget.options.values, promptName].sort((a, b) => a.localeCompare(b));
}
promptWidget.value = promptName;
textWidget.value = "";
// Mark as unsaved/new prompt
node.isNewUnsavedPrompt = true;
node.newPromptCategory = targetCategory;
node.newPromptName = promptName;
// Update previous values so cancel/revert works correctly
node._previousCategory = targetCategory;
node._previousPrompt = promptName;
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
});
const savePromptBtn = createButton("Save Prompt", async () => {
const promptName = await showTextPrompt("Save Prompt", "Enter prompt name:", promptWidget.value || "New Prompt");
if (promptName && promptName.trim()) {
const promptText = textWidget.value;
if (promptText && promptText.trim()) {
const currentCategory = categoryWidget.value;
// More dropdown button
const moreBtn = createDropdownButton("More ▼", [
{
label: "New Category",
action: async () => {
const categoryName = await showTextPrompt("New Category", "Enter new category name:");
// Case-insensitive check for existing prompt
let existingPromptName = null;
if (node.prompts[currentCategory]) {
const existingNames = Object.keys(node.prompts[currentCategory]);
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.trim().toLowerCase());
}
if (categoryName && categoryName.trim()) {
let existingCategoryName = null;
if (node.prompts) {
const existingCategories = Object.keys(node.prompts);
existingCategoryName = existingCategories.find(cat => cat.toLowerCase() === categoryName.trim().toLowerCase());
}
// Ask for confirmation before overwriting existing prompt
if (existingPromptName) {
const confirmed = await showConfirm(
"Overwrite Prompt",
`Prompt "${existingPromptName}" already exists in category "${currentCategory}". Do you want to overwrite it?`,
"Overwrite",
"#f80"
);
if (!confirmed) {
if (existingCategoryName) {
await showInfo(
"Category Exists",
`Category already exists as "${existingCategoryName}".`
);
return;
}
}
await savePrompt(node, categoryWidget.value, promptName.trim(), promptText.trim());
} else {
await showInfo("Empty Prompt", "Prompt text cannot be empty");
await createCategory(node, categoryName.trim());
}
}
},
{
label: "Delete Category",
action: async () => {
if (await showConfirm("Delete Category", `Are you sure you want to delete category "${categoryWidget.value}" and all its prompts?`)) {
await deleteCategory(node, categoryWidget.value);
}
}
},
{
label: "Delete Prompt",
action: async () => {
if (await showConfirm("Delete Prompt", `Are you sure you want to delete prompt "${promptWidget.value}"?`)) {
await deletePrompt(node, categoryWidget.value, promptWidget.value);
}
}
},
{ divider: true },
{
label: "Export JSON",
action: async () => {
await exportPromptsJSON(node);
}
},
{
label: "Import JSON",
action: async () => {
await importPromptsJSON(node);
}
}
});
const deleteCategoryBtn = createButton("Del Category", async () => {
if (await showConfirm("Delete Category", `Are you sure you want to delete category "${categoryWidget.value}"?`)) {
await deleteCategory(node, categoryWidget.value);
}
});
const deletePromptBtn = createButton("Del Prompt", async () => {
if (await showConfirm("Delete Prompt", `Are you sure you want to delete prompt "${promptWidget.value}"?`)) {
await deletePrompt(node, categoryWidget.value, promptWidget.value);
}
});
]);
buttonContainer.appendChild(savePromptBtn);
buttonContainer.appendChild(createCategoryBtn);
buttonContainer.appendChild(deleteCategoryBtn);
buttonContainer.appendChild(deletePromptBtn);
buttonContainer.appendChild(newPromptBtn);
buttonContainer.appendChild(moreBtn);
// Add button bar to node
const htmlWidget = node.addDOMWidget("buttons", "div", buttonContainer);
// Add button bar to node with proper options to avoid clipping issues
const htmlWidget = node.addDOMWidget("buttons", "div", buttonContainer, {
hideOnZoom: true,
serialize: false
});
htmlWidget.computeSize = function(width) {
return [width, 34];
return [width, 36];
};
node.buttonBarAttached = true;
@@ -460,11 +617,14 @@ function setupCategoryChangeHandler(node) {
const originalCallback = categoryWidget.callback;
// Update prompt dropdown when category changes
categoryWidget.callback = function(value) {
categoryWidget.callback = async function(value) {
if (originalCallback) {
originalCallback.apply(this, arguments);
}
// Reload prompts from server to get latest changes from other tabs
await loadPrompts(node);
const category = value;
if (node.prompts && node.prompts[category]) {
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
@@ -493,15 +653,32 @@ function setupCategoryChangeHandler(node) {
const originalPromptCallback = promptWidget.callback;
// Update text widget when prompt selection changes
promptWidget.callback = function(value) {
promptWidget.callback = async function(value) {
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
// Reload prompts from server to get latest changes from other tabs
await loadPrompts(node);
const category = categoryWidget.value;
// Update prompt dropdown options in case prompts were deleted/added in another tab
if (node.prompts && node.prompts[category]) {
const promptNames = Object.keys(node.prompts[category]).sort((a, b) => a.localeCompare(b));
promptWidget.options.values = promptNames.length > 0 ? promptNames : [""];
// Check if selected prompt still exists after reload
if (!promptNames.includes(value)) {
// Prompt was deleted in another tab, switch to first available
value = promptNames.length > 0 ? promptNames[0] : "";
promptWidget.value = value;
}
}
// Only update text if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (!useExternal) {
const category = categoryWidget.value;
if (node.prompts && node.prompts[category] && node.prompts[category][value]) {
const promptData = node.prompts[category][value];
textWidget.value = promptData?.prompt || "";
@@ -650,6 +827,409 @@ function createButton(text, callback) {
return button;
}
function createDropdownButton(text, items) {
const container = document.createElement("div");
container.style.position = "relative";
container.style.flex = "1";
container.style.minWidth = "80px";
const button = document.createElement("button");
button.textContent = text;
button.style.width = "100%";
button.style.padding = "6px 8px";
button.style.cursor = "pointer";
button.style.backgroundColor = "#222";
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "11px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.height = "28px";
button.style.display = "flex";
button.style.alignItems = "center";
button.style.justifyContent = "center";
// Create dropdown and append to body to escape stacking context issues
const dropdown = document.createElement("div");
dropdown.style.cssText = `
position: fixed;
background: #2a2a2a;
border: 1px solid #555;
border-radius: 6px;
z-index: 999999;
display: none;
box-shadow: 0 4px 12px rgba(0,0,0,0.5);
min-width: 140px;
`;
document.body.appendChild(dropdown);
items.forEach(item => {
if (item.divider) {
const divider = document.createElement("div");
divider.style.cssText = "height: 1px; background: #444; margin: 4px 0;";
dropdown.appendChild(divider);
} else {
const menuItem = document.createElement("div");
menuItem.textContent = item.label;
menuItem.style.cssText = `
padding: 8px 12px;
cursor: pointer;
font-size: 11px;
color: #fff;
white-space: nowrap;
`;
menuItem.addEventListener("mouseenter", () => {
menuItem.style.backgroundColor = "#4a4a4a";
});
menuItem.addEventListener("mouseleave", () => {
menuItem.style.backgroundColor = "transparent";
});
menuItem.addEventListener("click", (e) => {
e.stopPropagation();
dropdown.style.display = "none";
item.action();
});
dropdown.appendChild(menuItem);
}
});
button.addEventListener("click", (e) => {
e.stopPropagation();
const isVisible = dropdown.style.display === "block";
if (isVisible) {
dropdown.style.display = "none";
} else {
// Position dropdown below the button
const rect = button.getBoundingClientRect();
dropdown.style.left = rect.left + "px";
dropdown.style.top = (rect.bottom + 2) + "px";
dropdown.style.display = "block";
}
});
// Close dropdown when clicking elsewhere
document.addEventListener("click", (e) => {
if (!dropdown.contains(e.target) && e.target !== button) {
dropdown.style.display = "none";
}
});
container.appendChild(button);
return container;
}
function showPromptWithCategory(title, message, defaultName, categories, defaultCategory) {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 320px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
// Build category options
const categoryOptions = categories.map(cat =>
`<option value="${cat}" ${cat === defaultCategory ? 'selected' : ''}>${cat}</option>`
).join('');
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 6px; color: #aaa; font-size: 12px;">Category:</div>
<select style="width: 100%; padding: 8px; margin-bottom: 12px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px;">
${categoryOptions}
</select>
<div style="margin-bottom: 6px; color: #aaa; font-size: 12px;">${message}</div>
<input type="text" value="${defaultName}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px; box-sizing: border-box;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
</div>
`;
const selectEl = dialog.querySelector("select");
const input = dialog.querySelector("input");
const okBtn = dialog.querySelector(".ok-btn");
const cancelBtn = dialog.querySelector(".cancel-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
const handleOk = () => {
resolve({ name: input.value, category: selectEl.value });
cleanup();
};
const handleCancel = () => {
resolve(null);
cleanup();
};
okBtn.onclick = handleOk;
cancelBtn.onclick = handleCancel;
overlay.onclick = handleCancel;
input.onkeydown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
handleOk();
} else if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
handleCancel();
}
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
input.focus();
input.select();
});
}
async function exportPromptsJSON(node) {
try {
const response = await fetch("/prompt-manager/get-prompts");
const data = await response.json();
const jsonStr = JSON.stringify(data, null, 2);
const blob = new Blob([jsonStr], { type: "application/json" });
// Try File System Access API first (works on localhost and https)
if (window.showSaveFilePicker) {
try {
const handle = await window.showSaveFilePicker({
suggestedName: "prompt_manager_data.json",
types: [{
description: "JSON Files",
accept: { "application/json": [".json"] }
}]
});
const writable = await handle.createWritable();
await writable.write(blob);
await writable.close();
await showInfo("Export Complete", "Prompts exported successfully!");
return;
} catch (err) {
// User cancelled the dialog
if (err.name === "AbortError") {
return;
}
// Fall back to download method if API fails
console.log("[PromptManager] Save picker failed, falling back to download:", err);
}
}
// Fallback: Prompt user for filename, then download
const filename = await showTextPrompt(
"Export Prompts",
"Enter filename for export:",
"prompt_manager_data.json"
);
if (!filename) {
return; // User cancelled
}
const finalFilename = filename.endsWith(".json") ? filename : filename + ".json";
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = finalFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
await showInfo("Export Complete", "Prompts exported successfully!");
} catch (error) {
console.error("[PromptManager] Error exporting prompts:", error);
await showInfo("Error", "Failed to export prompts");
}
}
async function importPromptsJSON(node) {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) {
resolve(false);
return;
}
try {
const text = await file.text();
const importedData = JSON.parse(text);
// Validate structure
if (typeof importedData !== 'object' || Array.isArray(importedData)) {
await showInfo("Error", "Invalid JSON structure. Expected an object with categories.");
resolve(false);
return;
}
// Ask user how to handle import
const importMode = await showImportOptions();
if (importMode === null) {
// User cancelled
resolve(false);
return;
}
// Send to backend
const response = await fetch("/prompt-manager/import-prompts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
data: importedData,
mode: importMode
})
});
const result = await response.json();
if (result.success) {
node.prompts = result.prompts;
updateDropdowns(node);
// Refresh the current prompt text
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
const textWidget = node.widgets.find(w => w.name === "text");
if (categoryWidget && promptWidget && textWidget) {
const category = categoryWidget.value;
const promptName = promptWidget.value;
if (node.prompts[category] && node.prompts[category][promptName]) {
textWidget.value = node.prompts[category][promptName].prompt || "";
}
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
await showInfo("Import Complete", `Successfully imported prompts!`);
resolve(true);
} else {
await showInfo("Error", result.error || "Failed to import prompts");
resolve(false);
}
} catch (error) {
console.error("[PromptManager] Error importing prompts:", error);
await showInfo("Error", "Failed to parse JSON file");
resolve(false);
}
};
input.click();
});
}
function showImportOptions() {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 320px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">Import Prompts</div>
<div style="margin-bottom: 20px; color: #ccc;">How do you want to import?<br><br>
<strong>Merge:</strong> Keep existing prompts, add/update from import<br>
<strong>Replace:</strong> Delete all existing, use import only
</div>
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="replace-btn" style="padding: 8px 16px; background: #c00; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Replace</button>
<button class="merge-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Merge</button>
</div>
`;
const mergeBtn = dialog.querySelector(".merge-btn");
const replaceBtn = dialog.querySelector(".replace-btn");
const cancelBtn = dialog.querySelector(".cancel-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
mergeBtn.onclick = () => {
resolve("merge");
cleanup();
};
replaceBtn.onclick = () => {
resolve("replace");
cleanup();
};
cancelBtn.onclick = () => {
resolve(null);
cleanup();
};
overlay.onclick = () => {
resolve(null);
cleanup();
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
mergeBtn.focus();
});
}
function showTextPrompt(title, message, defaultValue = "") {
return new Promise((resolve) => {
const dialog = document.createElement("div");
@@ -968,11 +1548,11 @@ async function savePrompt(node, category, name, text) {
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
alert(`Error: ${data.error}`);
await showInfo("Error", data.error || "Failed to save prompt");
}
} catch (error) {
console.error("[PromptManager] Error saving prompt:", error);
alert("Error saving prompt");
await showInfo("Error", "Failed to save prompt");
}
}
@@ -993,11 +1573,11 @@ async function deleteCategory(node, category) {
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
alert(`Error: ${data.error}`);
await showInfo("Error", data.error || "Failed to delete category");
}
} catch (error) {
console.error("[PromptManager] Error deleting category:", error);
alert("Error deleting category");
await showInfo("Error", "Failed to delete category");
}
}
@@ -1021,11 +1601,11 @@ async function deletePrompt(node, category, name) {
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
alert(`Error: ${data.error}`);
await showInfo("Error", data.error || "Failed to delete prompt");
}
} catch (error) {
console.error("[PromptManager] Error deleting prompt:", error);
alert("Error deleting prompt");
await showInfo("Error", "Failed to delete prompt");
}
}
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,12 +1,12 @@
"""
ComfyUI Apply LoRA Stack - Apply a LORA_STACK to model and clip
ComfyUI Prompt Apply LoRA - Apply a LORA_STACK to model and clip
"""
import folder_paths
import comfy.sd
import comfy.utils
class ApplyLoRAStack:
class PromptApplyLora:
"""
Apply a LoRA stack to a model and optionally a CLIP.
Takes a LORA_STACK (list of tuples) and applies each LoRA sequentially.
@@ -44,7 +44,7 @@ class ApplyLoRAStack:
# Get the LoRA path
lora_path = folder_paths.get_full_path("loras", lora_name)
if lora_path is None:
print(f"[ApplyLoRAStack] Warning: LoRA not found: {lora_name}")
print(f"[PromptApplyLora] Warning: LoRA not found: {lora_name}")
continue
# Load the LoRA
+2000
View File
File diff suppressed because it is too large Load Diff
+54 -4
View File
@@ -50,6 +50,12 @@ class PromptManager:
FUNCTION = "get_prompt"
OUTPUT_NODE = True
@classmethod
def VALIDATE_INPUTS(cls, name, **kwargs):
"""Allow any name value, including temporary unsaved prompts"""
# Return True to accept any value - this allows new prompts to be tested before saving
return True
@staticmethod
def get_prompts_path():
"""Get the path to the prompts JSON file in user/default folder"""
@@ -179,8 +185,8 @@ async def save_prompt(request):
name = data.get("name", "").strip()
text = data.get("text", "").strip()
if not category or not name or not text:
return server.web.json_response({"success": False, "error": "All fields are required"})
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and name are required"})
prompts = PromptManager.load_prompts()
@@ -197,12 +203,14 @@ async def save_prompt(request):
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
del prompts[category][old_name]
# Save prompt in dict, preserving any existing lora data from PromptManagerAdvanced
# Save prompt in dict, preserving any existing lora data, trigger words, and thumbnail from PromptManagerAdvanced
existing_data = prompts[category].get(name, {})
prompts[category][name] = {
"prompt": text,
"loras_a": existing_data.get("loras_a", []),
"loras_b": existing_data.get("loras_b", [])
"loras_b": existing_data.get("loras_b", []),
"trigger_words": existing_data.get("trigger_words", []),
"thumbnail": existing_data.get("thumbnail")
}
PromptManager.save_prompts(prompts)
@@ -259,3 +267,45 @@ async def delete_prompt(request):
except Exception as e:
print(f"[PromptManager] Error in delete_prompt API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager/import-prompts")
async def import_prompts(request):
"""API endpoint to import prompts from JSON"""
try:
data = await request.json()
imported_data = data.get("data", {})
mode = data.get("mode", "merge")
if not isinstance(imported_data, dict):
return server.web.json_response({"success": False, "error": "Invalid data format"})
if mode == "replace":
# Replace all existing prompts
PromptManager.save_prompts(imported_data)
return server.web.json_response({"success": True, "prompts": imported_data})
else:
# Merge with existing prompts
prompts = PromptManager.load_prompts()
for category, category_prompts in imported_data.items():
if not isinstance(category_prompts, dict):
continue
if category not in prompts:
prompts[category] = {}
for prompt_name, prompt_data in category_prompts.items():
# Merge prompt data, preserving structure
if isinstance(prompt_data, dict):
prompts[category][prompt_name] = prompt_data
elif isinstance(prompt_data, str):
# Legacy format: just the prompt text
prompts[category][prompt_name] = {"prompt": prompt_data}
PromptManager.save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
print(f"[PromptManager] Error in import_prompts API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
File diff suppressed because it is too large Load Diff
+2 -3
View File
@@ -1,7 +1,7 @@
[project]
name = "prompt-manager"
description = "Prompt Manager extension for ComfyUI, allowing user to both save and generate prompts, as well as save matching loras for each prompt."
version = "1.9.1"
description = "A comprehensive prompt management system for ComfyUI that saves complete workflow recipes including prompts, LoRAs, and their settings. Features AI-powered prompt generation, prompt extraction from ComfyUI/A1111 images and videos, and Dual LoRA Stack support for Wan workflows."
version = "1.13.5"
license = {file = "LICENSE"}
# classifiers = [
# # For OS-independent nodes (works on all operating systems)
@@ -34,4 +34,3 @@ DisplayName = "ComfyUI-Prompt-Manager"
Icon = ""
includes = []
# "requires-comfyui" = ">=1.0.0" # ComfyUI version compatibility
+193
View File
@@ -0,0 +1,193 @@
#!/usr/bin/env python3
"""
Organize Files by Workflow Presence
Standalone script to scan a folder and move files without workflow metadata
Defaults to "D:/ComfyUI/input" if no folder is provided.
"""
import json
import shutil
from pathlib import Path
try:
from PIL import Image
HAS_PIL = True
except ImportError:
HAS_PIL = False
print("ERROR: PIL/Pillow is required!")
print("Install with: pip install pillow")
input("Press Enter to exit...")
exit(1)
def check_png_workflow(file_path):
"""Check if PNG has workflow metadata (ComfyUI or A1111 format)"""
try:
with Image.open(file_path) as img:
# Check for ComfyUI workflow/prompt or A1111 parameters
return 'workflow' in img.info or 'prompt' in img.info or 'parameters' in img.info
except:
return False
def check_jpeg_workflow(file_path):
"""Check if JPEG/WebP has workflow metadata"""
try:
with Image.open(file_path) as img:
exif = img.getexif()
if exif and 0x9286 in exif:
return True
if hasattr(img, 'info'):
return any(key in img.info for key in ['workflow', 'prompt', 'parameters'])
except:
return False
def check_json_workflow(file_path):
"""Check if JSON file contains workflow data"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if isinstance(data, dict):
return 'nodes' in data or 'workflow' in data or any(
isinstance(v, dict) and 'class_type' in v for v in data.values()
)
except Exception as e:
print(f" (JSON parse error: {e})")
pass
return False
def check_video_workflow(file_path):
"""Check if video has workflow metadata using ffprobe executable"""
import subprocess
try:
# Use ffprobe to get video metadata in JSON format
result = subprocess.run(
['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', str(file_path)],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
data = json.loads(result.stdout)
if 'format' in data and 'tags' in data['format']:
tags = data['format']['tags']
# Check for common workflow metadata keys
return any(key.lower() in ['comment', 'workflow', 'prompt', 'parameters'] for key in tags)
return False
except FileNotFoundError:
# ffprobe not found in PATH
print(" (Skipping - ffprobe not found in PATH)")
return None # Return None to skip
except subprocess.TimeoutExpired:
print(" (Timeout reading video)")
return False
except Exception as e:
print(f" (Video probe error: {e})")
return False
def has_workflow_metadata(file_path):
"""Check if file has workflow metadata"""
ext = file_path.suffix.lower()
if ext == '.png':
return check_png_workflow(file_path)
elif ext in ['.jpg', '.jpeg', '.webp']:
return check_jpeg_workflow(file_path)
elif ext == '.json':
return check_json_workflow(file_path)
elif ext in ['.mp4', '.webm', '.mov', '.avi']:
return check_video_workflow(file_path)
return False
def main(folder_path=None):
print("=" * 60)
print("File Organizer - Separate files by workflow presence")
print("=" * 60)
if folder_path is None:
# Get folder from user
folder_input = input("\nEnter folder path to scan (default D:/ComfyUI/input): ").strip().strip('"')
if folder_input == "":
folder_path = Path("D:/ComfyUI/input")
else:
folder_path = Path(folder_input)
if not folder_path.exists():
print(f"\nERROR: Folder does not exist: {folder_path}")
input("Press Enter to exit...")
return
if not folder_path.is_dir():
print(f"\nERROR: Not a directory: {folder_path}")
input("Press Enter to exit...")
return
# Create no_workflow subfolder
no_workflow_path = folder_path / "no_workflow"
no_workflow_path.mkdir(exist_ok=True)
print(f"\nScanning: {folder_path}")
print(f"Moving files without workflow to: {no_workflow_path}")
print("=" * 60)
# Supported extensions
supported = {'.png', '.jpg', '.jpeg', '.webp', '.json', '.mp4', '.webm', '.mov', '.avi'}
files_with_workflow = []
files_without_workflow = []
files_skipped = []
# Scan only files in this directory (no subdirectories)
for file_path in folder_path.iterdir():
if not file_path.is_file():
continue
if file_path.suffix.lower() in supported:
print(f"Checking: {file_path.name}", end=' ... ')
try:
result = has_workflow_metadata(file_path)
if result is None:
# Skipped (e.g., video without ffmpeg)
files_skipped.append(file_path)
elif result:
print("✓ Has workflow")
files_with_workflow.append(file_path)
else:
print("✗ No workflow")
files_without_workflow.append(file_path)
except Exception as e:
print(f"ERROR: {e}")
# Summary
print("\n" + "=" * 60)
print(f"Files with workflow: {len(files_with_workflow)}")
print(f"Files without workflow: {len(files_without_workflow)}")
if files_skipped:
print(f"Files skipped: {len(files_skipped)}")
# Move files without workflow
if files_without_workflow:
print("\nMoving files without workflow...")
for file_path in files_without_workflow:
dest_path = no_workflow_path / file_path.name
try:
shutil.move(str(file_path), str(dest_path))
print(f" Moved: {file_path.name}")
except Exception as e:
print(f" ERROR moving {file_path.name}: {e}")
print("\nDone!")
input("Press Enter to exit...")
if __name__ == "__main__":
main()
+143
View File
@@ -0,0 +1,143 @@
"""
Test fuzzy LoRA matching logic
"""
import os
import re
def fuzzy_match_lora(lora_name, lora_files):
"""
Attempt to find a matching LoRA using fuzzy matching.
Handles renamed LoRAs by removing common WAN-related tokens.
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
Returns (matched_file, True) if found, (None, False) otherwise.
"""
# Tokens to remove for fuzzy matching (case-insensitive)
# Order matters: remove longer tokens first to avoid partial matches
wan_tokens = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
def normalize_name(name):
"""
Remove WAN tokens from name, treating underscores and hyphens as separators.
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
Returns list of remaining non-empty parts in lowercase.
"""
name_lower = name.lower()
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
# Replace each token with a placeholder to preserve boundaries
for token in wan_tokens:
# Use word boundary-aware replacement with _ or - as delimiter
# Replace [_-]token[_-], [_-]token, token[_-], or standalone token
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
name_lower = re.sub(pattern, '_', name_lower)
# Split by underscore or hyphen and filter out empty strings
parts = [p for p in re.split(r'[_-]', name_lower) if p]
return parts
# Normalize the search name
search_parts = normalize_name(os.path.splitext(lora_name)[0])
search_set = set(search_parts)
candidates = []
for lora_file in lora_files:
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
file_parts = normalize_name(file_name_no_ext)
file_set = set(file_parts)
# Check if all search parts are present in the file parts
if search_set.issubset(file_set):
# Calculate how well this matches (prefer closer matches)
extra_parts = len(file_set - search_set)
candidates.append((lora_file, file_name_no_ext, extra_parts))
if not candidates:
return None, False
# If only one match, return it
if len(candidates) == 1:
return candidates[0][0], True
# Multiple matches - prefer ones that match i2v/t2v from original if present
lora_name_lower = lora_name.lower()
has_i2v = 'i2v' in lora_name_lower
has_t2v = 't2v' in lora_name_lower
if has_i2v:
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
if i2v_matches:
candidates = i2v_matches
elif has_t2v:
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
if t2v_matches:
candidates = t2v_matches
# Return the match with fewest extra parts (closest match)
candidates.sort(key=lambda x: x[2])
return candidates[0][0], True
def test_fuzzy_matching():
"""Test various fuzzy matching scenarios"""
# Simulate available LoRA files
available_loras = [
"DR34LAY_I2V_14B_HIGH_V2.safetensors",
"DR34LAY_T2V_14B_HIGH_V2.safetensors",
"DR34LAY_I2V_A14B_LOW_V2.safetensors",
"SomeOther_I2V_LoRA.safetensors",
"ExactMatch.safetensors",
"MyLora_WAN_2_2_I2V_Style.safetensors",
"MyLora_Style.safetensors",
"CoolStyle_I2V (1).safetensors",
"CoolStyle_I2V.safetensors",
]
test_cases = [
("DR34LAY_HIGH_V2", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Renamed WAN LoRA (missing I2V, 14B)"),
("DR34LAY_HIGH_V2.safetensors", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Renamed WAN LoRA with extension"),
("DR34LAY_LOW_V2", "DR34LAY_I2V_A14B_LOW_V2.safetensors", "Renamed WAN LoRA (missing I2V, A14B)"),
("DR34LAY_I2V_HIGH_V2", "DR34LAY_I2V_14B_HIGH_V2.safetensors", "Has I2V - should prefer I2V match"),
("DR34LAY_T2V_HIGH_V2", "DR34LAY_T2V_14B_HIGH_V2.safetensors", "Has T2V - should prefer T2V match"),
("MyLora_Style", "MyLora_WAN_2_2_I2V_Style.safetensors", "Should match with WAN_2_2 removed"),
("CoolStyle_I2V", "CoolStyle_I2V (1).safetensors", "Should match ignoring (1) suffix"),
("ExactMatch", "ExactMatch.safetensors", "Exact match case"),
("NonExistent_LoRA", None, "Non-existent LoRA"),
]
print("=" * 80)
print("FUZZY LORA MATCHING TESTS")
print("=" * 80)
all_passed = True
for search_name, expected_match, description in test_cases:
result, found = fuzzy_match_lora(search_name, available_loras)
expected_found = expected_match is not None
passed = (found == expected_found and (not found or result == expected_match))
status = "[PASS]" if passed else "[FAIL]"
print(f"\n{status} {description}")
print(f" Search: '{search_name}'")
print(f" Expected: {expected_match}")
print(f" Got: {result}")
if not passed:
all_passed = False
print("\n" + "=" * 80)
if all_passed:
print("[SUCCESS] All tests passed!")
else:
print("[FAILURE] Some tests failed!")
print("=" * 80)
return all_passed
if __name__ == "__main__":
test_fuzzy_matching()
+100
View File
@@ -0,0 +1,100 @@
"""
Test LoRA extraction from workflow data
"""
import json
import sys
import os
from unittest.mock import Mock
# Add parent directory to path so we can import prompt_extractor
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# Mock ComfyUI and heavy dependencies
sys.modules['folder_paths'] = Mock()
sys.modules['server'] = Mock()
sys.modules['torch'] = Mock()
sys.modules['PIL'] = Mock()
from prompt_extractor import parse_workflow_for_prompts
def test_wan_workflow_with_shared_lora_loader():
"""
Test case: WAN workflow where both high and low noise models
connect to the same Power Lora Loader, but should still extract
separate lora stacks based on which model they feed into.
"""
# Load the problematic workflow
workflow_path = r"d:\ComfyUI\user\default\workflows\Unsaved Workflow (4).json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
# Parse the workflow
result = parse_workflow_for_prompts(None, workflow_data)
print("\n" + "=" * 80)
print("TEST: WAN Workflow with Shared LoRA Loader")
print("=" * 80)
print(f"\nPositive prompt: {result['positive_prompt'][:100] if result['positive_prompt'] else 'EMPTY'}...")
print(f"Negative prompt: {result['negative_prompt'][:100] if result['negative_prompt'] else 'EMPTY'}")
print(f"\nLoRAs Stack A (High): {len(result['loras_a'])} LoRAs")
for lora in result['loras_a']:
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
print(f"\nLoRAs Stack B (Low): {len(result['loras_b'])} LoRAs")
for lora in result['loras_b']:
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
print("\n" + "=" * 80)
# Assertions - verify we get both active and inactive LoRAs from connected nodes
assert len(result['loras_a']) > 0, "Stack A should have LoRAs (high noise)"
assert len(result['loras_b']) > 0, "Stack B should have LoRAs (low noise)"
# Verify that we have BOTH active and inactive LoRAs (as the extractor returns all)
all_loras = result['loras_a'] + result['loras_b']
has_active = any(lora.get('active', True) for lora in all_loras)
has_inactive = any(not lora.get('active', True) for lora in all_loras)
print(f"\nVerification: Has active LoRAs: {has_active}, Has inactive LoRAs: {has_inactive}")
print(f"Total LoRAs extracted: {len(all_loras)}")
# Note: This workflow uses subgraphs, so prompts might be inside the subgraph
# assert result['positive_prompt'], "Should have positive prompt"
print("\n[PASS] All tests passed!")
def test_non_wan_workflow():
"""
Test case: Regular workflow without high/low naming conventions.
Should fall back to position-based assignment (1st chain -> A, 2nd -> B)
"""
workflow_path = r"d:\ComfyUI\user\default\workflows\Unsaved Workflow.json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
result = parse_workflow_for_prompts(None, workflow_data)
print("\n" + "=" * 80)
print("TEST: Non-WAN Workflow (backward compatibility)")
print("=" * 80)
print(f"\nLoRAs Stack A: {len(result['loras_a'])} LoRAs")
print(f"LoRAs Stack B: {len(result['loras_b'])} LoRAs")
print("\n" + "=" * 80)
print("\n[PASS] Backward compatibility maintained!")
if __name__ == "__main__":
test_wan_workflow_with_shared_lora_loader()
test_non_wan_workflow()
+89
View File
@@ -0,0 +1,89 @@
"""
Test the specific workflow with disconnected LoRAs
"""
import json
import sys
import os
from unittest.mock import Mock
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# Mock dependencies
sys.modules['folder_paths'] = Mock()
sys.modules['server'] = Mock()
sys.modules['torch'] = Mock()
sys.modules['PIL'] = Mock()
from prompt_extractor import parse_workflow_for_prompts
def test_unsaved_workflow_3():
"""
Test the specific workflow that has disconnected LoRAs
"""
workflow_path = r"D:\ComfyUI\user\default\workflows\Unsaved Workflow (3).json"
if not os.path.exists(workflow_path):
print(f"Workflow file not found: {workflow_path}")
return
with open(workflow_path, 'r', encoding='utf-8') as f:
workflow_data = json.load(f)
result = parse_workflow_for_prompts(None, workflow_data)
# Filter to ACTIVE only (like the real PromptExtractor node does at lines 1565/1581)
active_loras_a = [lora for lora in result['loras_a'] if lora.get('active', True)]
active_loras_b = [lora for lora in result['loras_b'] if lora.get('active', True)]
print("\n" + "=" * 80)
print("TEST: Unsaved Workflow (3) - Should NOT include disconnected LoRAs")
print("=" * 80)
print(f"\nLoRAs Stack A (ALL): {len(result['loras_a'])} LoRAs")
for lora in result['loras_a'][:10]: # Show first 10
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
if len(result['loras_a']) > 10:
print(f" ... and {len(result['loras_a']) - 10} more")
print(f"\nLoRAs Stack A (ACTIVE ONLY): {len(active_loras_a)} LoRAs")
for lora in active_loras_a:
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
print(f"\nLoRAs Stack B (ALL): {len(result['loras_b'])} LoRAs")
for lora in result['loras_b'][:10]: # Show first 10
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
if len(result['loras_b']) > 10:
print(f" ... and {len(result['loras_b']) - 10} more")
print(f"\nLoRAs Stack B (ACTIVE ONLY): {len(active_loras_b)} LoRAs")
for lora in active_loras_b:
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
print("\n" + "=" * 80)
# Check for the disconnected LoRAs in ACTIVE lists only
active_lora_names_a = [lora['name'] for lora in active_loras_a]
active_lora_names_b = [lora['name'] for lora in active_loras_b]
has_23high = any('23High noise-Cumshot' in name for name in active_lora_names_a + active_lora_names_b)
has_56low = any('56Low noise-Cumshot' in name for name in active_lora_names_a + active_lora_names_b)
print("\nDisconnected LoRA check (in ACTIVE lists):")
print(f" '23High noise-Cumshot Aesthetics' found: {has_23high} (should be False)")
print(f" '56Low noise-Cumshot Aesthetics' found: {has_56low} (should be False)")
print(f"\nTotal ACTIVE LoRAs extracted: {len(active_loras_a) + len(active_loras_b)} (expected: 8)")
if has_23high or has_56low:
print("\n[FAIL] Disconnected/inactive LoRAs are appearing in active lists!")
elif len(active_loras_a) == 4 and len(active_loras_b) == 4:
print("\n[PASS] Disconnected/inactive LoRAs correctly excluded!")
else:
print(f"\n[FAIL] Expected 4 active LoRAs per stack, got {len(active_loras_a)} and {len(active_loras_b)}")
print("=" * 80 + "\n")
if __name__ == "__main__":
test_unsaved_workflow_3()