From 84426288883e18b49162315e74bf82bf0103ddfa Mon Sep 17 00:00:00 2001 From: c0ffymachyne Date: Sun, 8 Dec 2024 11:30:05 -0800 Subject: [PATCH] harmonics enhancer, license, readme updates, blacked --- .gitignore | 3 + LICENSE-CCA-ANY | 795 +++--------------- README.md | 58 +- __init__.py | 8 +- core/conversions.py | 6 +- core/io.py | 222 +++-- core/loudness.py | 14 +- core/matching.py | 5 +- core/mixing.py | 1 + core/plotting.py | 35 +- core/saturation.py | 104 +++ core/utilities.py | 22 +- core/widening.py | 335 ++++---- effects/SignalProcessingConvolutionReverb.py | 111 +-- effects/SignalProcessingPaulStretch.py | 90 +- effects/SignalProcessingPitchShifter.py | 50 +- effects/SignalProcessingStereoWidening.py | 70 +- generators/SignalProcessingPadSynth.py | 33 +- generators/SignalProcessingPadSynthChoir.py | 45 +- nodes.py | 49 +- processors/SignalProcessingBaxandallEQ.py | 217 +++-- processors/SignalProcessingFilter.py | 44 +- .../SignalProcessingHarmonicsEnhancer.py | 126 +++ processors/SignalProcessingLoadAudio.py | 30 +- processors/SignalProcessingLoudness.py | 13 +- processors/SignalProcessingMixdown.py | 42 +- processors/SignalProcessingNormalizer.py | 73 +- visuals/SignalProcessingSpectrogram.py | 63 +- visuals/SignalProcessingWaveform.py | 88 +- 29 files changed, 1430 insertions(+), 1322 deletions(-) create mode 100644 core/saturation.py create mode 100644 processors/SignalProcessingHarmonicsEnhancer.py diff --git a/.gitignore b/.gitignore index 82f9275..cf282e3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,9 @@ __pycache__/ # C extensions *.so +# development directories +audio/ + # Distribution / packaging .Python build/ diff --git a/LICENSE-CCA-ANY b/LICENSE-CCA-ANY index f288702..1625c17 100644 --- a/LICENSE-CCA-ANY +++ b/LICENSE-CCA-ANY @@ -1,674 +1,121 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - 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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -. - - 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 -. +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. \ No newline at end of file diff --git a/README.md b/README.md index d9cbc5d..0eea768 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # ComfyUI Signal Processing + ## THIS IS WORK IN PROGRESS REPOSITORY + This repo contains signal processing nodes for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) allowing for audio manipulation. @@ -11,7 +13,7 @@ This repo contains signal processing nodes for [ComfyUI](https://github.com/comf - **`LICENSE-APACHE-2`** Some components are built from parts of code licensed under "Apache License Version 2". - **`LICENSE-CCA-ANY`** Some components are built from parts of code licensed under "Creative Commons Zero v1.0 Universal" - +--- ### Latests Updates @@ -21,6 +23,7 @@ This repo contains signal processing nodes for [ComfyUI](https://github.com/comf - **`GPU support`** - ported some of the nodes to gpu to gain speed - **`Removed some nodes`** - if you want them back contact me through this repository. I am planning to add new nodes with better quality +--- ### Mastering Nodes @@ -30,29 +33,36 @@ The Baxandall EQ is a smooth, wide-band tone control circuit widely used in audi Its simple design and musical response make it ideal for achieving natural tonal adjustments. Implementation is using the standard shelf filter equations from the Audio EQ Cookbook by Robert Bristow-Johnson ---- - #### Parameters: - **`audio`** self explanatory... - **`bass_gain_db`** Bass gain in decibels - **`mid_gain_db`** Mid gain in decibels - **`treble_gain_db`** Treble gain in decibels - - **`low_freq`** : The corner frequency for the low shelf (e.g. ~100 Hz). - **`mid_freq`** : The center frequency for the mid peaking filter (e.g. ~1 kHz). - **`high_freq`** : The corner frequency for the high shelf (e.g. ~10 kHz). - - **`mid_q`** : Quality factor for the mid peaking band. Adjusting Q controls the bandwidth of the mid peak. A typical Q might be 0.7 for a broad bell. --- +### Enhance Harmonics + +Harmonic enhancer boosts selected harmonics to enrich the sound + +#### Parameters: + +- **`harmonincs`** comma separated numbers of harmonics to boost +- **`mode`** whether to automatically detect base frequency based on an audio or use manual setting +- **`base_frequency`** base frequency to use in manual mode +- **`gain_db`** How much to boost harmonics +- **`gain_db`** Width of the filters + +--- ### Normalizer -Normalizer is an amalgamate of multiple normalization approaches, including Loudness Units Full Scale (LUFS) wit standard default set to -14db. - ---- +Normalizer is an amalgamate of multiple normalization approaches, including Loudness Units Full Scale (LUFS) with standard default set to -14db. ### Parametes @@ -66,14 +76,12 @@ Normalizer is an amalgamate of multiple normalization approaches, including Loud --- - ### Loudness The get_loudness function calculates the integrated loudness of an audio signal in LUFS (Loudness Units relative to Full Scale). This is a perceptual measure of loudness, taking into account the human ear's sensitivity to different frequencies and the entire audio signal's duration. --- - ### SignalProcessingStereoWidening: Open Source Stere Widening Plugin. The implementation is a direct copy of parts of the source code corresponding to this [paper](https://www.dafx.de/paper-archive/2024/papers/DAFx24_paper_92.pdf) developed by Orchisama Das. The code is distributed under `**CC0 1.0 Universal**` license. [Original Source Code](https://github.com/orchidas/StereoWidener) @@ -88,7 +96,6 @@ Open Source Stere Widening Plugin. The implementation is a direct copy of parts --- - ### Effects Nodes ### Convolution Reverb @@ -96,12 +103,12 @@ Open Source Stere Widening Plugin. The implementation is a direct copy of parts Convolution reverb simulates realistic acoustic spaces by applying the impulse response of a physical environment to an audio signal. It captures the natural reverberation characteristics, providing authentic spatial depth and ambience. -## How do I use it ? + +### How do I use it ? I recommend downloading impulse response files from this location [Voxengo-IR](https://oramics.github.io/sampled/IR/Voxengo/) and [Greg Hopkins EMT 140 Plate Reverb Impulse Response](https://oramics.github.io/sampled/IR/EMT140-Plate/). They sound absolutely fantastic and have great licensing. In order for the files to show up for selection in the convolution reverb please download the files and organize them like this : -- `comfyui_singalprocessing/audio/ir/Voxengo/` <- copy wave files into this directory -- `comfyui_singalprocessing/audio/ir/EMT-140-Plate/` <- copy wav files into this directory - +- `comfyui_signalprocessing/audio/ir/Voxengo/` <- copy wave files into this directory +- `comfyui_signalprocessing/audio/ir/EMT-140-Plate/` <- copy wav files into this directory #### Parameters: @@ -111,14 +118,12 @@ I recommend downloading impulse response files from this location [Voxengo-IR](h --- - ### SignalProcessingPaulStretch PaulStretch excels at extreme time-stretching with high-quality results, preserving the pitch and tonal characteristics of the original audio. This node contains a port of algorithm developed by Nasca Octavian Paul. [Original Source Code](https://github.com/paulnasca/paulstretch_python) - #### Parameters: - **`audio`** @@ -135,14 +140,12 @@ This node contains a port of algorithm developed by Nasca Octavian Paul. --- - ### SignalProcessingPadSynth : This node is a synthesiser "PadSynth" based on a PADSynth algorithm This node contains a port of algorithm developed by Nasca Octavian Paul [Original Source Code](https://zynaddsubfx.sourceforge.io/doc/PADsynth/PADsynth.htm) - #### Parameters: - **`samplerate`**: samplerate @@ -158,8 +161,6 @@ This node contains a port of algorithm developed by Nasca Octavian Paul This node is a synthesiser "PadSynth" emulating choirs [Original Source Code](https://zynaddsubfx.sourceforge.io/doc/PADsynth/PADsynth.htm) ---- - #### Parameters: - **`samplerate`**: samplerate @@ -169,11 +170,14 @@ This node is a synthesiser "PadSynth" emulating choirs - **`bandwidth_cents`**: bandwidth cents - **`number_harmonics`**: number of harmonics to produce +--- ### SignalProcessingFilter : Classic filters +#### Parameters: + - **`audio`**: input audio - **`cutoff`**: filter cutoff - **`filter_type`**: filter type - "lowpass", "highpass", "bandpass", "bandstop" @@ -181,11 +185,9 @@ Classic filters --- - ### SignalProcessingMixdown mixdown outputs from PadSynths with volume control per note - #### Parameters: - **`audios`**: audios input @@ -193,19 +195,15 @@ mixdown outputs from PadSynths with volume control per note --- - ### Testing/Visualization Nodes This section contains nodes enabling basic analysis and development of other nodes --- - ### SignalProcessingSpectrogram Renders Mel Spectrum Into An Image ---- - #### Parameters: - **`audio`**: audio input @@ -213,13 +211,10 @@ Renders Mel Spectrum Into An Image --- - ### SignalProcessingWaveform Renders Wave Shape Into An Image ---- - #### Parameters: - **`audio`**: audio input @@ -227,7 +222,6 @@ Renders Wave Shape Into An Image --- - ### SignalProcessingLoadAudio : This node lets you stretch audio to about 100x it's original speed whil mainting pitch. it's great for making pad sounds: @@ -235,4 +229,4 @@ This node lets you stretch audio to about 100x it's original speed whil mainting #### Parameters: - **`audio_file`**: input audio file -- **`gain`**: when to start audio from +- **`gain`**: when to start audio from \ No newline at end of file diff --git a/__init__.py b/__init__.py index 1e43cf8..4a5e877 100644 --- a/__init__.py +++ b/__init__.py @@ -1,2 +1,8 @@ from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS -__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS','SignalProcessingFilter','SignalProcessingLoadAudio'] \ No newline at end of file + +__all__ = [ + "NODE_CLASS_MAPPINGS", + "NODE_DISPLAY_NAME_MAPPINGS", + "SignalProcessingFilter", + "SignalProcessingLoadAudio", +] diff --git a/core/conversions.py b/core/conversions.py index 306fcd5..8019ae9 100644 --- a/core/conversions.py +++ b/core/conversions.py @@ -11,13 +11,15 @@ Description: import torch + def db_to_lin(value): - return 10**(value / 20) + return 10 ** (value / 20) + def lin_to_tb(value): return 20 * torch.log10(torch.abs(value) + 1.0e-24) + def get_sign(value): sign = torch.sign(value) return sign - diff --git a/core/io.py b/core/io.py index ba7407e..1d7224e 100644 --- a/core/io.py +++ b/core/io.py @@ -16,18 +16,23 @@ import numpy as np # this mess needs some cleanup !! + # when we return audio to comfy, turn it to cpu -def audio_to_comfy_3d(waveform : torch.Tensor ,sample_rate: int, cpu = True, clip : bool = False) -> Tuple[Dict]: +def audio_to_comfy_3d( + waveform: torch.Tensor, sample_rate: int, cpu=True, clip: bool = False +) -> Tuple[Dict]: # try to fix wrong shape - if (waveform.ndim == 2): + if waveform.ndim == 2: waveform = waveform.unsqueeze(0) - - if (waveform.ndim != 3): - raise RuntimeError(f"returning to_comfy failed {waveform.shape}@{waveform.device}[{waveform.ndim}] has incorrect dimentions, it should be of dimension [batch,channels,audio]") + + if waveform.ndim != 3: + raise RuntimeError( + f"returning to_comfy failed {waveform.shape}@{waveform.device}[{waveform.ndim}] has incorrect dimentions, it should be of dimension [batch,channels,audio]" + ) if cpu: - if waveform.device != 'cpu': + if waveform.device != "cpu": waveform = waveform.cpu() if waveform.dtype != torch.float64: @@ -36,24 +41,31 @@ def audio_to_comfy_3d(waveform : torch.Tensor ,sample_rate: int, cpu = True, cli if clip: waveform = np.clip(waveform, -1.0, 1.0) - return_value = ({'waveform':waveform, 'sample_rate': sample_rate},) + return_value = ({"waveform": waveform, "sample_rate": sample_rate},) - print(f"audio_to_comfy_3d '{return_value}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_to_comfy_3d '{return_value}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) return return_value + # when we return audio to comfy, turn it to cpu -def audio_to_comfy_3dp1(waveform : torch.Tensor ,sample_rate: int, value0 : Any, cpu = True, clip : bool = False) -> Tuple[Dict]: +def audio_to_comfy_3dp1( + waveform: torch.Tensor, sample_rate: int, value0: Any, cpu=True, clip: bool = False +) -> Tuple[Dict]: # try to fix wrong shape - if (waveform.ndim == 2): + if waveform.ndim == 2: waveform = waveform.unsqueeze(0) - - if (waveform.ndim != 3): - raise RuntimeError(f"returning to_comfy failed {waveform.shape}@{waveform.device}dim[{waveform.ndim}] has incorrect dimentions, it should be of dimension [batch,channels,audio]") + + if waveform.ndim != 3: + raise RuntimeError( + f"returning to_comfy failed {waveform.shape}@{waveform.device}dim[{waveform.ndim}] has incorrect dimentions, it should be of dimension [batch,channels,audio]" + ) if cpu: - if waveform.device != 'cpu': + if waveform.device != "cpu": waveform = waveform.cpu() if waveform.dtype != torch.float64: @@ -62,24 +74,39 @@ def audio_to_comfy_3dp1(waveform : torch.Tensor ,sample_rate: int, value0 : Any, if clip: waveform = np.clip(waveform, -1.0, 1.0) - return_value = ({'waveform':waveform, 'sample_rate': sample_rate},value0,) + return_value = ( + {"waveform": waveform, "sample_rate": sample_rate}, + value0, + ) - print(f"audio_to_comfy_3d '{return_value}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_to_comfy_3d '{return_value}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) return return_value + # when we return audio to comfy, turn it to cpu -def audio_to_comfy_3dp2(waveform : torch.Tensor, sample_rate: int,value0 : Any, value1 : Any, cpu = True, clip: bool = False) -> Tuple[Dict]: +def audio_to_comfy_3dp2( + waveform: torch.Tensor, + sample_rate: int, + value0: Any, + value1: Any, + cpu=True, + clip: bool = False, +) -> Tuple[Dict]: # try to fix wrong shape - if (waveform.ndim == 2): + if waveform.ndim == 2: waveform = waveform.unsqueeze(0) - - if (waveform.ndim != 3): - raise RuntimeError(f"returning to_comfy failed {waveform.shape}@{waveform.device}dim[{waveform.ndim}] has incorrect dimentions, it should be of dimension [batch,channels,audio]") - + + if waveform.ndim != 3: + raise RuntimeError( + f"returning to_comfy failed {waveform.shape}@{waveform.device}dim[{waveform.ndim}] has incorrect dimentions, it should be of dimension [batch,channels,audio]" + ) + if cpu: - if waveform.device != 'cpu': + if waveform.device != "cpu": waveform = waveform.cpu() if waveform.dtype != torch.float64: @@ -88,20 +115,29 @@ def audio_to_comfy_3dp2(waveform : torch.Tensor, sample_rate: int,value0 : Any, if clip: waveform = np.clip(waveform, -1.0, 1.0) - return_value = ({'waveform':waveform, 'sample_rate': sample_rate}, value0, value1,) + return_value = ( + {"waveform": waveform, "sample_rate": sample_rate}, + value0, + value1, + ) - print(f"audio_to_comfy_3d '{return_value}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_to_comfy_3d '{return_value}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) return return_value + # when we get audio from comfy, load it to gpu -def audio_from_comfy_2d(audio : Tuple[Dict], repeat=True, try_gpu = True) -> Tuple[torch.Tensor,int]: +def audio_from_comfy_2d( + audio: Tuple[Dict], repeat=True, try_gpu=True +) -> Tuple[torch.Tensor, int]: if audio is None: raise ValueError("Input audio must be provided.") - waveform = audio.get('waveform') # [batch, channels, samples] - sample_rate = audio.get('sample_rate') + waveform = audio.get("waveform") # [batch, channels, samples] + sample_rate = audio.get("sample_rate") if waveform.dtype != torch.float64: waveform = waveform.to(dtype=torch.float64) @@ -112,34 +148,43 @@ def audio_from_comfy_2d(audio : Tuple[Dict], repeat=True, try_gpu = True) -> Tup if not isinstance(waveform, torch.Tensor): raise TypeError("Waveform must be a torch.Tensor.") - print(f"audio_from_comfy_2d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_from_comfy_2d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) if waveform.ndim != 3: - raise ValueError(f"Waveform must be a 3D tensor with shape (batch, channels, samples) not {waveform.shape}@{waveform.device}") + raise ValueError( + f"Waveform must be a 3D tensor with shape (batch, channels, samples) not {waveform.shape}@{waveform.device}" + ) if repeat: - if waveform.ndim == 1: # add extra channel in case of mono + if waveform.ndim == 1: # add extra channel in case of mono print(f"audio_from_comfy_2d repeat") - waveform = waveform.unsqueeze(0) # Add channel dimension - waveform = waveform.repeat(2, 1) # copy mono to the new channel + waveform = waveform.unsqueeze(0) # Add channel dimension + waveform = waveform.repeat(2, 1) # copy mono to the new channel waveform = waveform.squeeze(0).contiguous() if try_gpu: - device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") waveform = waveform.to(device) - print(f"audio_from_comfy_2d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_from_comfy_2d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) return waveform, sample_rate -def audio_from_comfy_3d(audio : Tuple[Dict], repeat=True, try_gpu = True) -> Tuple[torch.Tensor,int]: + +def audio_from_comfy_3d( + audio: Tuple[Dict], repeat=True, try_gpu=True +) -> Tuple[torch.Tensor, int]: if audio is None: raise ValueError("Input audio must be provided.") - waveform = audio.get('waveform') # [batch, channels, samples] - sample_rate = audio.get('sample_rate') + waveform = audio.get("waveform") # [batch, channels, samples] + sample_rate = audio.get("sample_rate") if waveform.dtype != torch.float64: waveform = waveform.to(dtype=torch.float64) @@ -150,41 +195,52 @@ def audio_from_comfy_3d(audio : Tuple[Dict], repeat=True, try_gpu = True) -> Tup if not isinstance(waveform, torch.Tensor): raise TypeError("Waveform must be a torch.Tensor.") - print(f"audio_from_comfy_2d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_from_comfy_2d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) if waveform.ndim != 3: - raise ValueError(f"Waveform must be a 3D tensor with shape (batch, channels, samples) not {waveform.shape}@{waveform.device}") + raise ValueError( + f"Waveform must be a 3D tensor with shape (batch, channels, samples) not {waveform.shape}@{waveform.device}" + ) if repeat: - if waveform.ndim == 1: # add extra channel in case of mono + if waveform.ndim == 1: # add extra channel in case of mono print(f"audio_from_comfy_2d repeat") - waveform = waveform.unsqueeze(0) # Add channel dimension - waveform = waveform.repeat(2, 1) # copy mono to the new channel + waveform = waveform.unsqueeze(0) # Add channel dimension + waveform = waveform.repeat(2, 1) # copy mono to the new channel - #waveform = waveform.squeeze(0).contiguous() + # waveform = waveform.squeeze(0).contiguous() if try_gpu: - device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") waveform = waveform.to(device) - print(f"audio_from_comfy_3d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"audio_from_comfy_3d with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) return waveform, sample_rate - -def from_disk_as_dict_3d(audio_file : str, gain: float = 1.0, repeat = True, start_time : float = 0.0, end_time : float = 0.0) -> Dict: +def from_disk_as_dict_3d( + audio_file: str, + gain: float = 1.0, + repeat=True, + start_time: float = 0.0, + end_time: float = 0.0, +) -> Dict: # all loaded audio comes in 3 dimensions - #[batch,channels,audio] 3 dimensions + # [batch,channels,audio] 3 dimensions if not Path(audio_file).exists(): raise ValueError(f"File {audio_file} Does Not Exist") - info= torchaudio.info(audio_file) + info = torchaudio.info(audio_file) sample_rate = info.sample_rate # cut sudio segment - if (start_time > 0.0) and (end_time > start_time): + if (start_time > 0.0) and (end_time > start_time): frame_offset = int(start_time * sample_rate) # Start frame num_frames = int((end_time - start_time) * sample_rate) # Total frames to read waveform, sample_rate = torchaudio.load( @@ -198,67 +254,81 @@ def from_disk_as_dict_3d(audio_file : str, gain: float = 1.0, repeat = True, sta waveform = waveform * gain if repeat: - if waveform.ndim == 1: # add extra channel in case of mono - waveform = waveform.repeat(2, 1) # copy mono to the new channel + if waveform.ndim == 1: # add extra channel in case of mono + waveform = waveform.repeat(2, 1) # copy mono to the new channel # add batch dimension at the front waveform = waveform.unsqueeze(0).contiguous() - #waveform = waveform * gain + # waveform = waveform * gain - print(f"from_disk_as_dict_3d loaded audio file: '{audio_file}' with shape: {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate: {sample_rate} Hz.") + print( + f"from_disk_as_dict_3d loaded audio file: '{audio_file}' with shape: {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate: {sample_rate} Hz." + ) - return audio_to_comfy_3d(waveform,sample_rate) + return audio_to_comfy_3d(waveform, sample_rate) -def from_disk_as_raw_3d(audio_file : str, repeat : bool = True, try_gpu : bool = False) -> Tuple[torch.Tensor, int]: +def from_disk_as_raw_3d( + audio_file: str, repeat: bool = True, try_gpu: bool = False +) -> Tuple[torch.Tensor, int]: # all loaded audio comes in 3 dimensions - #[batch,channels,audio] 3 dimensions + # [batch,channels,audio] 3 dimensions waveform, sample_rate = torchaudio.load(audio_file) - info= torchaudio.info(audio_file) - print(f"from_disk_as_raw_3d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + info = torchaudio.info(audio_file) + print( + f"from_disk_as_raw_3d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) if waveform.dtype != torch.float64: waveform = waveform.to(dtype=torch.float64) if repeat: - if info.num_channels == 1: # add extra channel in case of mono - waveform = waveform.repeat(2, 1) # copy mono to the new channel + if info.num_channels == 1: # add extra channel in case of mono + waveform = waveform.repeat(2, 1) # copy mono to the new channel # add batch dimension at the front waveform = waveform.unsqueeze(0).contiguous() if try_gpu: - device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") waveform = waveform.to(device) - print(f"from_disk_as_raw_3d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"from_disk_as_raw_3d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) return waveform, sample_rate -def from_disk_as_raw_2d(audio_file : str, repeat : bool = True, try_gpu : bool = False) -> Tuple[torch.Tensor, int]: + +def from_disk_as_raw_2d( + audio_file: str, repeat: bool = True, try_gpu: bool = False +) -> Tuple[torch.Tensor, int]: # all loaded audio comes in 3 dimensions - #[batch,channels,audio] 3 dimensions + # [batch,channels,audio] 3 dimensions waveform, sample_rate = torchaudio.load(audio_file) - info= torchaudio.info(audio_file) + info = torchaudio.info(audio_file) - print(f"from_disk_as_raw_2d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"from_disk_as_raw_2d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) if waveform.dtype != torch.float64: waveform = waveform.to(dtype=torch.float64) - + if repeat: - if info.num_channels == 1: # add extra channel in case of mono - waveform = waveform.repeat(2, 1) # copy mono to the new channel - #waveform = waveform.unsqueeze(0) # Add channel dimension + if info.num_channels == 1: # add extra channel in case of mono + waveform = waveform.repeat(2, 1) # copy mono to the new channel + # waveform = waveform.unsqueeze(0) # Add channel dimension if try_gpu: - device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") waveform = waveform.to(device) - - print(f"from_disk_as_raw_2d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz.") + print( + f"from_disk_as_raw_2d loaded audio file: '{audio_file}' with shape {waveform.shape}@{waveform.device}dim[{waveform.ndim}] and sample rate {sample_rate} Hz." + ) - return waveform, sample_rate \ No newline at end of file + return waveform, sample_rate diff --git a/core/loudness.py b/core/loudness.py index 0ca9436..2caa921 100644 --- a/core/loudness.py +++ b/core/loudness.py @@ -14,38 +14,44 @@ import pyloudnorm as pyln # pip install pyloudnorm import torch -def rms_normalization(audio : torch.Tensor, target_rms : float =0.1): +def rms_normalization(audio: torch.Tensor, target_rms: float = 0.1): rms = torch.sqrt(torch.mean(audio**2)) scaling_factor = target_rms / rms normalized_audio = audio * scaling_factor return normalized_audio -def lufs_normalization(audio : torch.Tensor, sample_rate : float, target_lufs : float = -14.0): + +def lufs_normalization( + audio: torch.Tensor, sample_rate: float, target_lufs: float = -14.0 +): meter = pyln.Meter(sample_rate) # Create a loudness meter audio = audio.T.cpu().numpy() loudness = meter.integrated_loudness(audio) # Current LUFS loudness_offset = target_lufs - loudness - normalized_audio = audio * (10**(loudness_offset / 20.0)) + normalized_audio = audio * (10 ** (loudness_offset / 20.0)) result = torch.from_numpy(normalized_audio) result = result.T return result + def peak_normalization(audio, target_peak=0.9): peak = torch.max(torch.abs(audio)) scaling_factor = target_peak / peak normalized_audio = audio * scaling_factor return normalized_audio -def get_loudness(audio : torch.Tensor, sample_rate : float) -> float: + +def get_loudness(audio: torch.Tensor, sample_rate: float) -> float: meter = pyln.Meter(sample_rate) # Create a loudness meter audio = audio.T audio = audio.cpu() loudness = meter.integrated_loudness(audio.numpy()) # Current LUFS return loudness + def automatic_gain_control(audio, target_level=0.7, alpha=0.1): current_level = torch.mean(torch.abs(audio)) gain = target_level / (current_level + 1e-6) diff --git a/core/matching.py b/core/matching.py index 0e9e09a..9faae15 100644 --- a/core/matching.py +++ b/core/matching.py @@ -17,9 +17,10 @@ from torch.optim import Adam def approximate_loudness_matching(audio, target_loudness=-14.0): rms = torch.sqrt(torch.mean(audio**2)) current_loudness = 20 * torch.log10(rms + 1e-6) - gain = 10**((target_loudness - current_loudness) / 20.0) + gain = 10 ** ((target_loudness - current_loudness) / 20.0) return audio * gain + def waveform_matching(audio, target_audio, lr=0.01, steps=100): audio = audio.clone().requires_grad_(True) optimizer = Adam([audio], lr=lr) @@ -29,5 +30,5 @@ def waveform_matching(audio, target_audio, lr=0.01, steps=100): optimizer.zero_grad() loss.backward() optimizer.step() - + return audio.detach() diff --git a/core/mixing.py b/core/mixing.py index 995f766..f20a034 100644 --- a/core/mixing.py +++ b/core/mixing.py @@ -11,6 +11,7 @@ Description: import torch + def combine_audio_files(waveform_a, waveform_b, sample_rate, chunk_duration=2.0): """ Combine two audio files by alternating 2-second chunks, cropping to the shorter audio. diff --git a/core/plotting.py b/core/plotting.py index a27587c..e498c91 100644 --- a/core/plotting.py +++ b/core/plotting.py @@ -15,7 +15,8 @@ from PIL import Image import numpy as np import matplotlib.pyplot as plt -def _figure_to_image(figure,format='png',dpi=96): + +def _figure_to_image(figure, format="png", dpi=96): buf = BytesIO() figure.savefig(buf, format=format, dpi=96) plt.close(figure) @@ -25,26 +26,33 @@ def _figure_to_image(figure,format='png',dpi=96): return waveform_image -def get_wave(waveform : torch.Tensor, sample_rate : int , title : str ="Waveform", xlim=None, ylim=None): + +def get_wave( + waveform: torch.Tensor, + sample_rate: int, + title: str = "Waveform", + xlim=None, + ylim=None, +): waveform = waveform.numpy() - + num_channels, num_frames = waveform.shape time_axis = torch.arange(0, num_frames) / sample_rate - + figure, axes = plt.subplots(num_channels, 1) if num_channels == 1: axes = [axes] for c in range(num_channels): axes[c].plot(time_axis, waveform[c], linewidth=1) axes[c].grid(True) - + if num_channels > 1: - axes[c].set_ylabel(f'Channel {c+1}') + axes[c].set_ylabel(f"Channel {c+1}") if xlim: axes[c].set_xlim(xlim) if ylim: axes[c].set_ylim(ylim) - + figure.suptitle(title) waveform_image = _figure_to_image(figure) @@ -52,18 +60,20 @@ def get_wave(waveform : torch.Tensor, sample_rate : int , title : str ="Waveform return waveform_image -def get_spectogram(waveform : torch.Tensor, sample_rate : int , title="Spectrogram", xlim=None): +def get_spectogram( + waveform: torch.Tensor, sample_rate: int, title="Spectrogram", xlim=None +): waveform = waveform.numpy() num_channels, num_frames = waveform.shape time_axis = torch.arange(0, num_frames) / sample_rate - + figure, axes = plt.subplots(num_channels, 1) if num_channels == 1: axes = [axes] for c in range(num_channels): axes[c].specgram(waveform[c], Fs=sample_rate) if num_channels > 1: - axes[c].set_ylabel(f'Channel {c+1}') + axes[c].set_ylabel(f"Channel {c+1}") if xlim: axes[c].set_xlim(xlim) figure.suptitle(title) @@ -72,5 +82,6 @@ def get_spectogram(waveform : torch.Tensor, sample_rate : int , title="Spectrogr return waveform_image -def save_image(filepath : str, image : Image): - image.save(filepath, format="JPEG", quality=95) \ No newline at end of file + +def save_image(filepath: str, image: Image): + image.save(filepath, format="JPEG", quality=95) diff --git a/core/saturation.py b/core/saturation.py new file mode 100644 index 0000000..d306b58 --- /dev/null +++ b/core/saturation.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Author: C0ffymachyne +License: GPLv3 +Version: 1.0.0 + +Description: + various conversion methods +""" + +import math +import torch +from torch import nn + +class TubeValveSimulator: + def __init__(self, sample_rate, coefficients=None): + """ + Initialize the Tube/Valve simulator using Volterra Series Expansion. + + Args: + sample_rate (int): The sample rate of the audio signal. + coefficients (dict): Coefficients for Volterra series terms. + Example: {'linear': 1.0, 'quadratic': 0.5, 'cubic': 0.2} + """ + self.sample_rate = sample_rate + self.coefficients = coefficients if coefficients else { + 'linear': 1.0, + 'quadratic': 0.5, + 'cubic': 0.2, + } + + def process(self, audio_input): + """ + Process the audio signal to simulate tube/valve characteristics. + + Args: + audio_input (torch.Tensor): The input audio signal (1D or 2D tensor). + + Returns: + torch.Tensor: The processed audio signal. + """ + # Ensure input is a float tensor + #audio_input = audio_input.to(torch.float32) + + # Volterra series expansion + linear_term = self.coefficients['linear'] * audio_input + quadratic_term = self.coefficients['quadratic'] * audio_input**2 + cubic_term = self.coefficients['cubic'] * audio_input**3 + + # Combine the terms + processed_audio = linear_term + quadratic_term + cubic_term + + # Optional soft clipping to simulate saturation + #processed_audio = self.soft_clip(processed_audio) + + return processed_audio + + @staticmethod + def soft_clip(audio_signal, threshold=0.9): + """ + Apply soft clipping to the audio signal to limit extreme values. + + Args: + audio_signal (torch.Tensor): The input audio signal. + threshold (float): The clipping threshold. + + Returns: + torch.Tensor: The clipped audio signal. + """ + return torch.tanh(audio_signal / threshold) * threshold + +######################################## +# Example Usage +######################################## +if __name__ == "__main__": + + from pathlib import Path + import torchaudio + from core.io import from_disk_as_raw_2d, audio_to_comfy_3d, audio_from_comfy_2d + + samples_path = Path("/media/broot/zyzx/git/ComfyUI-0.2.4/custom_nodes/ComfyUI_SignalProcessing/audio/inputs/baxandall-normalizer_00003_.flac") + + source_path = samples_path.absolute() + source_audio, source_audio_sample_rate = from_disk_as_raw_2d(source_path,try_gpu=True) + input = audio_to_comfy_3d(source_audio, source_audio_sample_rate)[0] + + + # Initialize the simulator + tube_simulator = TubeValveSimulator(source_audio_sample_rate, coefficients={ + 'linear': 1.0, + 'quadratic': 0.3, + 'cubic': 0.4, + }) + + compressed = tube_simulator.process(source_audio) + print("Compressed shape:", compressed.shape) + print("Device:", compressed.device) + + torchaudio.save( + "audio/outputs/valve.wav", + compressed.cpu(), + source_audio_sample_rate, + ) diff --git a/core/utilities.py b/core/utilities.py index 2e94856..6fdcb50 100644 --- a/core/utilities.py +++ b/core/utilities.py @@ -9,7 +9,7 @@ Description: various development utilities """ -import os +import os import sys import re @@ -18,34 +18,34 @@ pattern = r"^ComfyUI-\d+\.\d+\.\d+$" this_file_directory = os.path.join(os.path.dirname(os.path.realpath(__file__))) + def find_comfy_root(): path = os.fspath(this_file_directory) if isinstance(this_file_directory, bytes): - sep = b'/' + sep = b"/" else: - sep = '/' + sep = "/" tokens = path.split(sep) while not re.match(pattern, tokens[-1]): print(tokens[-1]) tokens.pop(-1) - - path = '/'.join(tokens) + + path = "/".join(tokens) return path + # add comfy to path for local devepment only # find comfy root by going upwards hoping it match regex # export coffy_local_dev=1 def comfy_root_to_syspath(): try: - if os.environ['coffy_local_dev'] == '1': - print('coffy_local_dev') + if os.environ["coffy_local_dev"] == "1": + print("coffy_local_dev") else: - raise(Exception()) + raise (Exception()) except: return path = find_comfy_root() if path not in sys.path: - sys.path.insert(0,path) - - + sys.path.insert(0, path) diff --git a/core/widening.py b/core/widening.py index 9ac68e3..789d1c8 100644 --- a/core/widening.py +++ b/core/widening.py @@ -20,7 +20,6 @@ Description: """ - import os import pyfar as pf import numpy as np @@ -35,14 +34,15 @@ from scipy.signal import fftconvolve this_directory = os.path.dirname(os.path.realpath(__file__)) -data_directory = os.path.join(os.path.split(this_directory)[0],'data','widener') +data_directory = os.path.join(os.path.split(this_directory)[0], "data", "widener") -VN_PATH = Path(f'{data_directory}/init_vn_filters.txt') -OPT_VN_PATH = Path(f'{data_directory}/opt_vn_filters.txt') +VN_PATH = Path(f"{data_directory}/init_vn_filters.txt") +OPT_VN_PATH = Path(f"{data_directory}/opt_vn_filters.txt") print(VN_PATH.absolute()) print(os.path.dirname(os.path.realpath(__file__))) + class FilterbankType(Enum): AMP_PRESERVE = "amplitude-preserve" ENERGY_PRESERVE = "energy-preserve" @@ -53,6 +53,7 @@ class DecorrelationType(Enum): VELVET = "velvet" OPT_VELVET = "opt_velvet" + import numpy as np from numpy.typing import ArrayLike, NDArray from typing import List @@ -60,6 +61,7 @@ import matplotlib.pyplot as plt _HIGH_EPS = 1e9 + def ms_to_samps(ms: npt.NDArray[float], /, fs: float) -> npt.NDArray[int]: """Calculate the nearest integer number of samples corresponding to the given time duration in milliseconds. @@ -72,6 +74,7 @@ def ms_to_samps(ms: npt.NDArray[float], /, fs: float) -> npt.NDArray[int]: """ return np.round(ms * 1e-3 * fs).astype(int) + def half_hann_fade(length: int, fade_out: bool = False) -> npt.NDArray: """Generate a half Hann window for fading out or in a signal. @@ -86,8 +89,8 @@ def half_hann_fade(length: int, fade_out: bool = False) -> npt.NDArray: fade: npt.NDArray = 0.5 - 0.5 * np.cos(np.pi * (n + int(fade_out))) return fade -def warp_pole_angle(rho: float, pole_freq: Union[float, - np.ndarray]) -> npt.NDArray: + +def warp_pole_angle(rho: float, pole_freq: Union[float, np.ndarray]) -> npt.NDArray: """ Warp pole angles according to warping factor rho Args: @@ -101,9 +104,9 @@ def warp_pole_angle(rho: float, pole_freq: Union[float, return np.imag(lambdam) -def decorrelate_allpass_filters(fs: float, - nbiquads: int = 250, - max_grp_del_ms: float = 30.): +def decorrelate_allpass_filters( + fs: float, nbiquads: int = 250, max_grp_del_ms: float = 30.0 +): """ Return cascaded allpass SOS sections with randomised phase to perform signal decorrelation Args: @@ -121,29 +124,30 @@ def decorrelate_allpass_filters(fs: float, ap_pole_freq = np.random.uniform(low=0, high=2 * np.pi, size=nbiquads) # warp pole angles to ERB filterbank - warp_factor = 0.7464 * np.sqrt( - 2.0 / np.pi * np.arctan(0.1418 * fs)) + 0.03237 + warp_factor = 0.7464 * np.sqrt(2.0 / np.pi * np.arctan(0.1418 * fs)) + 0.03237 ap_pole_freq_warped = warp_pole_angle(warp_factor, ap_pole_freq) # allpass filter biquad cascade poles = ap_rad * np.exp(1j * ap_pole_freq_warped) sos_sec = np.zeros((nbiquads, 6)) # numerator coefficients - sos_sec[:, 0] = np.abs(poles)**2 + sos_sec[:, 0] = np.abs(poles) ** 2 sos_sec[:, 1] = -2 * np.real(poles) sos_sec[:, 2] = np.ones(nbiquads) # denominator coefficients sos_sec[:, 3] = np.ones(nbiquads) sos_sec[:, 4] = -2 * np.real(poles) - sos_sec[:, 5] = np.abs(poles)**2 + sos_sec[:, 5] = np.abs(poles) ** 2 return sos_sec -def process_allpass(input_signal: np.ndarray, - fs: float, - num_biquads: int = 200, - max_grp_del_ms: float = 30.0) -> np.ndarray: +def process_allpass( + input_signal: np.ndarray, + fs: float, + num_biquads: int = 200, + max_grp_del_ms: float = 30.0, +) -> np.ndarray: """ For an input stereo signal, pass both channels through cascade of allpass filters, and return the output @@ -160,20 +164,21 @@ def process_allpass(input_signal: np.ndarray, for chan in range(num_channels): sos_section[chan, ...] = decorrelate_allpass_filters( - fs, nbiquads=num_biquads, max_grp_del_ms=max_grp_del_ms) - output_signal[:, chan] = sosfilt(sos_section[chan, ...], - input_signal[:, chan], - zi=None) + fs, nbiquads=num_biquads, max_grp_del_ms=max_grp_del_ms + ) + output_signal[:, chan] = sosfilt( + sos_section[chan, ...], input_signal[:, chan], zi=None + ) return output_signal -class LeakyIntegrator(): + +class LeakyIntegrator: """Leaky integrator for signal envelope detection""" - def __init__(self, - fs: float, - attack_time_ms: float = 5.0, - release_time_ms: float = 50.0): + def __init__( + self, fs: float, attack_time_ms: float = 5.0, release_time_ms: float = 50.0 + ): self.fs = fs self.attack_time_ms = attack_time_ms self.release_time_ms = release_time_ms @@ -194,7 +199,7 @@ class LeakyIntegrator(): """ # find envelope with a leaky integrator - if (input_signal.ndim == 2 and input_signal.shape[1] > 1): + if input_signal.ndim == 2 and input_signal.shape[1] > 1: input_signal = input_signal[:, 0] tau_a = self.attack_time_ms * self.fs * 1e-3 @@ -203,27 +208,29 @@ class LeakyIntegrator(): signal_env = np.zeros_like(input_signal) for n in range(1, signal_length): if input_signal[n] > signal_env[n - 1]: - signal_env[n] = signal_env[n - 1] + ( - 1 - np.exp(-1 / tau_a)) * (np.abs(input_signal[n]) - - signal_env[n - 1]) + signal_env[n] = signal_env[n - 1] + (1 - np.exp(-1 / tau_a)) * ( + np.abs(input_signal[n]) - signal_env[n - 1] + ) else: - signal_env[n] = signal_env[n - 1] + ( - 1 - np.exp(-1 / tau_r)) * (np.abs(input_signal[n]) - - signal_env[n - 1]) + signal_env[n] = signal_env[n - 1] + (1 - np.exp(-1 / tau_r)) * ( + np.abs(input_signal[n]) - signal_env[n - 1] + ) return signal_env -class OnsetDetector(): +class OnsetDetector: """ Onset detector with a leaky integrator""" - def __init__(self, - fs: float, - attack_time_ms: float = 5.0, - release_time_ms: float = 20.0, - min_onset_hold_ms: float = 80.0, - min_onset_sep_ms: float = 50.0): + def __init__( + self, + fs: float, + attack_time_ms: float = 5.0, + release_time_ms: float = 20.0, + min_onset_hold_ms: float = 80.0, + min_onset_sep_ms: float = 50.0, + ): """ Args: fs (float): sampling rate in Hz @@ -237,8 +244,7 @@ class OnsetDetector(): self.fs = fs self.leaky = LeakyIntegrator(fs, attack_time_ms, release_time_ms) self._onset_flag = [] - self.min_onset_hold_samps = int(ms_to_samps(min_onset_hold_ms, - self.fs)) + self.min_onset_hold_samps = int(ms_to_samps(min_onset_hold_ms, self.fs)) self.min_onset_sep_samps = int(ms_to_samps(min_onset_sep_ms, self.fs)) self._threshold = None self._signal_env = None @@ -271,12 +277,11 @@ class OnsetDetector(): return False @staticmethod - def check_direction(cur_samp: float, - prev_samp: float, - next_samp: float, - is_rising: bool = True) -> bool: + def check_direction( + cur_samp: float, prev_samp: float, next_samp: float, is_rising: bool = True + ) -> bool: """ - Check whether the signal envelope is rising or falling. + Check whether the signal envelope is rising or falling. The flag `is_rising` is used to check for rising envelopes """ if is_rising: @@ -286,7 +291,7 @@ class OnsetDetector(): def process(self, input_signal: NDArray, to_plot: bool = False): """Given an input signal, find the location of onsets""" - if (input_signal.ndim == 2 and input_signal.shape[1] > 1): + if input_signal.ndim == 2 and input_signal.shape[1] > 1: input_signal = input_signal[:, 0] num_samp = len(input_signal) self._signal_env = self.leaky.process(input_signal) @@ -304,16 +309,17 @@ class OnsetDetector(): prev_samp = self._signal_env[k - 1] next_samp = self._signal_env[k + 1] - is_local_peak = self.check_local_peak(cur_samp, prev_samp, - next_samp) + is_local_peak = self.check_local_peak(cur_samp, prev_samp, next_samp) # running sum of the signal envelope self._running_sum_thres += self.signal_env[k] # threshold is 1.4 * mean of envelope if there is a local peak - self._threshold[k] = 2 * (self._running_sum_thres / - k) if is_local_peak else self._threshold[ - k - 1] + self._threshold[k] = ( + 2 * (self._running_sum_thres / k) + if is_local_peak + else self._threshold[k - 1] + ) # if an onset is detected, the flag will be true for a minimum number # of frames to prevent false offset detection @@ -333,15 +339,15 @@ class OnsetDetector(): # if the signal is rising and the value is greater than the # mean of the thresholds so far if self.check_direction( - cur_samp, prev_samp, next_samp, - is_rising=True) and cur_samp > (self._threshold[k]): + cur_samp, prev_samp, next_samp, is_rising=True + ) and cur_samp > (self._threshold[k]): self._onset_flag[k] = True hold_counter += 1 # if the signal is fallng and the value is lesser than the # mean of the thresholds so far elif self.check_direction( - cur_samp, prev_samp, next_samp, - is_rising=False) and cur_samp < (self._threshold[k]): + cur_samp, prev_samp, next_samp, is_rising=False + ) and cur_samp < (self._threshold[k]): self._onset_flag[k] = False inhibit_counter += 1 @@ -357,19 +363,20 @@ class OnsetDetector(): onset_pos[onset_idx] = 1.0 fig, ax = plt.subplots(figsize=(6, 4)) - ax.plot(time_vector, input_signal, label='input signal') - ax.plot(time_vector, self._signal_env, label='envelope') - ax.plot(time_vector, self._threshold, label='threshold') - ax.plot(time_vector, onset_pos, 'k--', label='onsets') - ax.legend(loc='lower left') + ax.plot(time_vector, input_signal, label="input signal") + ax.plot(time_vector, self._signal_env, label="envelope") + ax.plot(time_vector, self._threshold, label="threshold") + ax.plot(time_vector, onset_pos, "k--", label="onsets") + ax.legend(loc="lower left") ax.set_ylim([-1.0, 1.0]) plt.show() return ax -def process_velvet(input_signal: np.ndarray, - fs: float, - vn_seq_path: Optional[Path] = None) -> np.ndarray: + +def process_velvet( + input_signal: np.ndarray, fs: float, vn_seq_path: Optional[Path] = None +) -> np.ndarray: """Process a stereo input with two channels of VN sequence""" _, num_channels = input_signal.shape if num_channels > 2: @@ -379,37 +386,41 @@ def process_velvet(input_signal: np.ndarray, raise RuntimeError("Input signal must be stereo!") try: - vn_seq = np.loadtxt(vn_seq_path, dtype='f', delimiter=" ") + vn_seq = np.loadtxt(vn_seq_path, dtype="f", delimiter=" ") except: raise OSError("Error reading file!") output_signal = np.zeros_like(input_signal) for chan in range(num_channels): - output_signal[:, chan] = fftconvolve( - input_signal[:, chan], vn_seq[chan, :])[:output_signal.shape[0]] + output_signal[:, chan] = fftconvolve(input_signal[:, chan], vn_seq[chan, :])[ + : output_signal.shape[0] + ] return output_signal + class StereoWidener(ABC): """Parent stereo widener class""" - def __init__(self, - input_stereo: np.ndarray, - fs: float, - decorr_type: DecorrelationType, - beta: float, - detect_transient: bool = False, - onset_detection_params: Optional[Dict] = None, - xfade_win_len_ms: float = 1.0): - """Args: - input_stereo (ndarray) : input stereo signal - fs (float) : sampling frequency - decorr_type (Decorrelation type) : decorrelation type (allpass, velvet or opt_velvet) - beta (between 0 and pi/2): crossfading factor (initial) - detect_transient (bool): whether to add a transient detection block - onset_detection_params (dict, optional): dictionary of parameters for onset detection - xfade_win_len_ms (float): crossfading window used during transients - """ + def __init__( + self, + input_stereo: np.ndarray, + fs: float, + decorr_type: DecorrelationType, + beta: float, + detect_transient: bool = False, + onset_detection_params: Optional[Dict] = None, + xfade_win_len_ms: float = 1.0, + ): + """Args: + input_stereo (ndarray) : input stereo signal + fs (float) : sampling frequency + decorr_type (Decorrelation type) : decorrelation type (allpass, velvet or opt_velvet) + beta (between 0 and pi/2): crossfading factor (initial) + detect_transient (bool): whether to add a transient detection block + onset_detection_params (dict, optional): dictionary of parameters for onset detection + xfade_win_len_ms (float): crossfading window used during transients + """ self.input_signal = input_stereo self.fs = fs @@ -429,30 +440,26 @@ class StereoWidener(ABC): if onset_detection_params is not None: self.onset_detector = OnsetDetector( self.fs, - min_onset_hold_ms=onset_detection_params[ - 'min_onset_hold_ms'], - min_onset_sep_ms=onset_detection_params['min_onset_sep_ms'] + min_onset_hold_ms=onset_detection_params["min_onset_hold_ms"], + min_onset_sep_ms=onset_detection_params["min_onset_sep_ms"], ) else: self.onset_detector = OnsetDetector(self.fs) - self.xfade_win_len_samps = int( - ms_to_samps(xfade_win_len_ms, self.fs)) - self.xfade_in_win = half_hann_fade(self.xfade_win_len_samps, - fade_out=False) - self.xfade_out_win = half_hann_fade(self.xfade_win_len_samps, - fade_out=True) + self.xfade_win_len_samps = int(ms_to_samps(xfade_win_len_ms, self.fs)) + self.xfade_in_win = half_hann_fade(self.xfade_win_len_samps, fade_out=False) + self.xfade_out_win = half_hann_fade(self.xfade_win_len_samps, fade_out=True) def decorrelate_input(self) -> np.ndarray: if self.decorr_type == DecorrelationType.ALLPASS: - decorrelated_signal = process_allpass(self.input_signal, - self.fs, - num_biquads=200) + decorrelated_signal = process_allpass( + self.input_signal, self.fs, num_biquads=200 + ) elif self.decorr_type == DecorrelationType.VELVET: - decorrelated_signal = process_velvet(self.input_signal, self.fs, - VN_PATH) + decorrelated_signal = process_velvet(self.input_signal, self.fs, VN_PATH) elif self.decorr_type == DecorrelationType.OPT_VELVET: - decorrelated_signal = process_velvet(self.input_signal, self.fs, - OPT_VN_PATH) + decorrelated_signal = process_velvet( + self.input_signal, self.fs, OPT_VN_PATH + ) else: raise NotImplementedError("Other decorrelators are not available") return decorrelated_signal @@ -465,30 +472,43 @@ class StereoWidener(ABC): def process(self): pass -def filter_in_subbands(input_signal: np.ndarray, - fs: int, - bands_per_octave: int = 3, - freq_range=(20, 16000), - filter_length: int = 4096) -> Tuple[npt.NDArray, npt.NDArray]: - + +def filter_in_subbands( + input_signal: np.ndarray, + fs: int, + bands_per_octave: int = 3, + freq_range=(20, 16000), + filter_length: int = 4096, +) -> Tuple[npt.NDArray, npt.NDArray]: + signal = pf.classes.audio.Signal(input_signal, fs) - signal_subband, centre_frequencies = pf.dsp.filter.reconstructing_fractional_octave_bands(signal, - bands_per_octave, freq_range, n_samples=filter_length) + signal_subband, centre_frequencies = ( + pf.dsp.filter.reconstructing_fractional_octave_bands( + signal, bands_per_octave, freq_range, n_samples=filter_length + ) + ) return signal_subband.time, centre_frequencies -def calculate_interchannel_coherence(x: np.ndarray, y: np.ndarray, time_axis: int) -> npt.NDArray: - return np.abs(np.sum(x * y, axis=time_axis)) / np.sqrt(np.sum(x**2, axis=time_axis) * np.sum(y**2, axis=time_axis)) + +def calculate_interchannel_coherence( + x: np.ndarray, y: np.ndarray, time_axis: int +) -> npt.NDArray: + return np.abs(np.sum(x * y, axis=time_axis)) / np.sqrt( + np.sum(x**2, axis=time_axis) * np.sum(y**2, axis=time_axis) + ) -def calculate_interchannel_cross_correlation_matrix(signals: np.ndarray, - fs: int, - num_channels: int, - time_axis: int = -1, - channel_axis: int = 0, - return_single_coeff: bool = False, - bands_per_octave: int = 3, - freq_range=(20,16000)): +def calculate_interchannel_cross_correlation_matrix( + signals: np.ndarray, + fs: int, + num_channels: int, + time_axis: int = -1, + channel_axis: int = 0, + return_single_coeff: bool = False, + bands_per_octave: int = 3, + freq_range=(20, 16000), +): """Returns a matrix of ICC values for each channel axis in signals""" if time_axis != -1: signals = np.moveaxis(signals, 0, 1) @@ -497,11 +517,9 @@ def calculate_interchannel_cross_correlation_matrix(signals: np.ndarray, # passthrough filterbank if not return_single_coeff: - signals_subband, centre_frequencies = filter_in_subbands(signals, - fs, - bands_per_octave=bands_per_octave, - freq_range=freq_range - ) + signals_subband, centre_frequencies = filter_in_subbands( + signals, fs, bands_per_octave=bands_per_octave, freq_range=freq_range + ) num_f = len(centre_frequencies) # make sure the channel axis is in the beginning signals_subband = np.moveaxis(signals_subband, 1, 0) @@ -515,11 +533,15 @@ def calculate_interchannel_cross_correlation_matrix(signals: np.ndarray, if i == j: continue if return_single_coeff: - icc_matrix[i, j] = calculate_interchannel_coherence(signals[i, :], signals[j, :], time_axis=time_axis) + icc_matrix[i, j] = calculate_interchannel_coherence( + signals[i, :], signals[j, :], time_axis=time_axis + ) else: - icc_matrix[:, i, j] = calculate_interchannel_coherence(signals_subband[i, :, :], - signals_subband[j, :, :], - time_axis=time_axis) + icc_matrix[:, i, j] = calculate_interchannel_coherence( + signals_subband[i, :, :], + signals_subband[j, :, :], + time_axis=time_axis, + ) if return_single_coeff: return icc_matrix else: @@ -528,10 +550,15 @@ def calculate_interchannel_cross_correlation_matrix(signals: np.ndarray, class StereoWidenerFrequencyBased(StereoWidener): - def __init__(self, input_stereo: np.ndarray, fs: float, - filterbank_type: FilterbankType, - decorr_type: DecorrelationType, beta: Tuple[float, float], - cutoff_freq: float): + def __init__( + self, + input_stereo: np.ndarray, + fs: float, + filterbank_type: FilterbankType, + decorr_type: DecorrelationType, + beta: Tuple[float, float], + cutoff_freq: float, + ): """Frequency based stereo widener Args: input_stereo (ndarray): input stereo signal @@ -550,14 +577,15 @@ class StereoWidenerFrequencyBased(StereoWidener): def get_filter_coefficients(self): if self.filterbank_type == FilterbankType.AMP_PRESERVE: # Linkwitz Riley crossover filterbank - filters = pf.dsp.filter.crossover(signal=None, - N=4, - frequency=self.cutoff_freq, - sampling_rate=self.fs) + filters = pf.dsp.filter.crossover( + signal=None, N=4, frequency=self.cutoff_freq, sampling_rate=self.fs + ) self.lowpass_filter_coeffs = pf.classes.filter.FilterSOS( - filters.coefficients[0, ...], self.fs) + filters.coefficients[0, ...], self.fs + ) self.highpass_filter_coeffs = pf.classes.filter.FilterSOS( - filters.coefficients[1, ...], self.fs) + filters.coefficients[1, ...], self.fs + ) elif self.filterbank_type == FilterbankType.ENERGY_PRESERVE: @@ -565,19 +593,22 @@ class StereoWidenerFrequencyBased(StereoWidener): signal=None, N=16, frequency=self.cutoff_freq, - btype='lowpass', - sampling_rate=self.fs) + btype="lowpass", + sampling_rate=self.fs, + ) self.highpass_filter_coeffs = pf.dsp.filter.butterworth( signal=None, N=16, frequency=self.cutoff_freq, - btype='highpass', - sampling_rate=self.fs) + btype="highpass", + sampling_rate=self.fs, + ) else: raise NotImplementedError( - "Only Butterworth and LR crossover filters are available") + "Only Butterworth and LR crossover filters are available" + ) def filter_in_subbands(self, signal: np.ndarray) -> np.ndarray: """Filter signal into two frequency bands""" @@ -595,20 +626,21 @@ class StereoWidenerFrequencyBased(StereoWidener): def process(self): stereo_output = np.zeros_like(self.input_signal) - filtered_input = np.zeros( - (2, self.input_signal.shape[0], self.num_channels)) + filtered_input = np.zeros((2, self.input_signal.shape[0], self.num_channels)) filtered_decorr = np.zeros_like(filtered_input) for chan in range(self.num_channels): filtered_input[..., chan] = self.filter_in_subbands( - self.input_signal[:, chan]) + self.input_signal[:, chan] + ) filtered_decorr[..., chan] = self.filter_in_subbands( - self.decorrelated_signal[:, chan]) + self.decorrelated_signal[:, chan] + ) for k in range(self.num_channels): stereo_output[:, chan] += np.cos(self.beta[k]) * np.squeeze( - filtered_input[k, :, chan]) + np.sin( - self.beta[k]) * np.squeeze(filtered_decorr[k, :, chan]) + filtered_input[k, :, chan] + ) + np.sin(self.beta[k]) * np.squeeze(filtered_decorr[k, :, chan]) return stereo_output @@ -620,6 +652,7 @@ class StereoWidenerFrequencyBased(StereoWidener): time_axis=0, channel_axis=-1, bands_per_octave=3, - freq_range=(20, self.fs / 2.0)) + freq_range=(20, self.fs / 2.0), + ) icc_vector = np.squeeze(icc_matrix[..., 0, 1]) - return icc_vector, icc_freqs \ No newline at end of file + return icc_vector, icc_freqs diff --git a/effects/SignalProcessingConvolutionReverb.py b/effects/SignalProcessingConvolutionReverb.py index 38927c1..3e299cd 100644 --- a/effects/SignalProcessingConvolutionReverb.py +++ b/effects/SignalProcessingConvolutionReverb.py @@ -9,13 +9,14 @@ Description: Convolution Reverb """ -import os +import os import torch, torchaudio import torch.nn.functional as F from pathlib import Path from ..core.utilities import comfy_root_to_syspath -comfy_root_to_syspath() # add comfy to sys path for dev + +comfy_root_to_syspath() # add comfy to sys path for dev from ..core.io import audio_from_comfy_2d, audio_to_comfy_3d, from_disk_as_raw_2d from ..core.loudness import lufs_normalization, get_loudness @@ -24,16 +25,18 @@ from ..core.loudness import lufs_normalization, get_loudness import folder_paths -class SignalProcessingConvolutionReverb(): - supported_formats = ['.wav','.mp3','.ogg','.m4a','.flac','.mp4'] +class SignalProcessingConvolutionReverb: + supported_formats = [".wav", ".mp3", ".ogg", ".m4a", ".flac", ".mp4"] this_directory = os.path.dirname(os.path.realpath(__file__)) - ir_directory = os.path.join(os.path.split(this_directory)[0],'audio','ir') + ir_directory = os.path.join(os.path.split(this_directory)[0], "audio", "ir") @classmethod def INPUT_TYPES(s): - - files, _ = folder_paths.recursive_search(SignalProcessingConvolutionReverb.ir_directory) - + + files, _ = folder_paths.recursive_search( + SignalProcessingConvolutionReverb.ir_directory + ) + ir_files = [] for file in files: try: @@ -44,15 +47,18 @@ class SignalProcessingConvolutionReverb(): pass return { - "required": { - "impulse_response": ( sorted(ir_files), ), - "audio_input": ("AUDIO", ), - "wet_dry":("FLOAT", { - "default": 0.5, - "min": 0.0, - "max": 1.0, - "step": 0.01, - }), + "required": { + "impulse_response": (sorted(ir_files),), + "audio_input": ("AUDIO",), + "wet_dry": ( + "FLOAT", + { + "default": 0.5, + "min": 0.0, + "max": 1.0, + "step": 0.01, + }, + ), }, } @@ -63,41 +69,48 @@ class SignalProcessingConvolutionReverb(): def process(self, impulse_response, audio_input, wet_dry): - try_gpu : bool = True - repeat : bool = True + try_gpu: bool = True + repeat: bool = True print(impulse_response) print(audio_input) - waveform, sample_rate = audio_from_comfy_2d(audio_input,repeat=repeat,try_gpu=try_gpu) + waveform, sample_rate = audio_from_comfy_2d( + audio_input, repeat=repeat, try_gpu=try_gpu + ) - loudness = get_loudness(waveform,sample_rate) + loudness = get_loudness(waveform, sample_rate) - it_filepath = os.path.join(SignalProcessingConvolutionReverb.ir_directory,impulse_response) - ir,ir_sr = from_disk_as_raw_2d(it_filepath,repeat=repeat,try_gpu=try_gpu) + it_filepath = os.path.join( + SignalProcessingConvolutionReverb.ir_directory, impulse_response + ) + ir, ir_sr = from_disk_as_raw_2d(it_filepath, repeat=repeat, try_gpu=try_gpu) # Resample IR if sampling rates do not match if ir_sr != sample_rate: print(f"Resampling impulse response from {ir_sr} Hz to {sample_rate} Hz.") - resampler = torchaudio.transforms.Resample(orig_freq=ir_sr, new_freq=sample_rate).to(ir.device,dtype=waveform.dtype) + resampler = torchaudio.transforms.Resample( + orig_freq=ir_sr, new_freq=sample_rate + ).to(ir.device, dtype=waveform.dtype) ir = resampler(ir) ir_sr = sample_rate - print('ensure channels') - #if wave is mono and ir is not mono + print("ensure channels") + # if wave is mono and ir is not mono if waveform.shape[0] == 1 and ir.shape[0] == 2: - ir = ir.mean(dim=0, keepdim=True) + ir = ir.mean(dim=0, keepdim=True) if waveform.shape[0] == 2 and ir.shape[0] == 1: - ir = ir.repeat(2,1) + ir = ir.repeat(2, 1) - print('apply reverb') + print("apply reverb") processed_audio = self.apply_reverb(waveform, sample_rate, ir, wet_dry=wet_dry) - processed_audio = lufs_normalization(processed_audio,sample_rate,loudness) + processed_audio = lufs_normalization(processed_audio, sample_rate, loudness) - return audio_to_comfy_3d(processed_audio,sample_rate,cpu=True) + return audio_to_comfy_3d(processed_audio, sample_rate, cpu=True) - - def apply_reverb(self, audio: torch.Tensor, sr: int, ir: torch.Tensor, wet_dry: float = 0.5) -> torch.Tensor: + def apply_reverb( + self, audio: torch.Tensor, sr: int, ir: torch.Tensor, wet_dry: float = 0.5 + ) -> torch.Tensor: num_audio_channels, audio_length = audio.shape num_ir_channels, ir_length = ir.shape @@ -112,10 +125,14 @@ class SignalProcessingConvolutionReverb(): for channel in range(num_audio_channels): # Get the current audio and IR channel audio_channel = audio[channel].unsqueeze(0).unsqueeze(0) # Shape: [1, 1, N] - ir_channel = ir[channel].flip(0).unsqueeze(0).unsqueeze(0) # Reverse IR, Shape: [1, 1, M] + ir_channel = ( + ir[channel].flip(0).unsqueeze(0).unsqueeze(0) + ) # Reverse IR, Shape: [1, 1, M] # Perform convolution - convolved = F.conv1d(audio_channel, ir_channel, padding=ir_length - 1) # Shape: [1, 1, N + M -1] + convolved = F.conv1d( + audio_channel, ir_channel, padding=ir_length - 1 + ) # Shape: [1, 1, N + M -1] # Remove batch and channel dimensions convolved = convolved.squeeze(0).squeeze(0) # Shape: [N + M -1] @@ -129,7 +146,7 @@ class SignalProcessingConvolutionReverb(): convolved = convolved / max_val # Apply wet/dry mix - dry = (1 - wet_dry) + dry = 1 - wet_dry wet = wet_dry processed = dry * audio[channel] + wet * convolved @@ -156,24 +173,24 @@ if __name__ == "__main__": node = SignalProcessingConvolutionReverb() types = node.INPUT_TYPES() - samples_path = Path('ComfyUI_SignalProcessing/audio/samples') - impulses_path = Path('ComfyUI_SignalProcessing/audio/ir') + samples_path = Path("ComfyUI_SignalProcessing/audio/samples") + impulses_path = Path("ComfyUI_SignalProcessing/audio/ir") - samples = list(samples_path.rglob('*.*')) - impulses = list(impulses_path.rglob('*.*')) + samples = list(samples_path.rglob("*.*")) + impulses = list(impulses_path.rglob("*.*")) print(samples) s = samples[1].absolute() i = impulses[0].absolute() - s,sr= from_disk_as_raw_2d(s) + s, sr = from_disk_as_raw_2d(s) - sound = audio_to_comfy_3d(s,sr)[0] + sound = audio_to_comfy_3d(s, sr)[0] - result = node.process(i,sound,wet_dry=.5)[0] + result = node.process(i, sound, wet_dry=0.5)[0] audio, sr = audio_from_comfy_2d(result) - torchaudio.save('ComfyUI_SignalProcessing/audio/tests/reverb.wav',audio.cpu(),sr) + torchaudio.save("ComfyUI_SignalProcessing/audio/tests/reverb.wav", audio.cpu(), sr) - #set console to comfy ComfyUI-0.2.4/custom_nodes and run below command - #export coffy_local_dev=1 - #python3 -m ComfyUI_SingalProcessing.effects.SignalProcessingConvolutionReverb \ No newline at end of file + # set console to comfy ComfyUI-0.2.4/custom_nodes and run below command + # export coffy_local_dev=1 + # python3 -m ComfyUI_SingalProcessing.effects.SignalProcessingConvolutionReverb diff --git a/effects/SignalProcessingPaulStretch.py b/effects/SignalProcessingPaulStretch.py index 07494a1..bbc6325 100644 --- a/effects/SignalProcessingPaulStretch.py +++ b/effects/SignalProcessingPaulStretch.py @@ -19,19 +19,27 @@ import math from typing import Tuple, List, Dict from ..core.utilities import comfy_root_to_syspath -comfy_root_to_syspath() # add comfy to sys path for dev + +comfy_root_to_syspath() # add comfy to sys path for dev from ..core.io import audio_from_comfy_2d, audio_to_comfy_3d from ..core.loudness import lufs_normalization, get_loudness + class SignalProcessingPaulStretch: @classmethod def INPUT_TYPES(cls) -> Dict: return { "required": { "audio": ("AUDIO", {"forceInput": True}), - "stretch_factor": ("FLOAT", {"default": 8.0, "min": 1.0, "max": 100.0, "step": 0.1}), - "window_size_seconds": ("FLOAT", {"default": 0.25, "min": 0.05, "max": 10.0, "step": 0.05}), + "stretch_factor": ( + "FLOAT", + {"default": 8.0, "min": 1.0, "max": 100.0, "step": 0.1}, + ), + "window_size_seconds": ( + "FLOAT", + {"default": 0.25, "min": 0.05, "max": 10.0, "step": 0.05}, + ), } } @@ -44,15 +52,15 @@ class SignalProcessingPaulStretch: self, audio: Dict[str, torch.Tensor], stretch_factor: float, - window_size_seconds: float + window_size_seconds: float, ) -> Tuple[Dict[str, torch.Tensor]]: # Conditional processing: If stretch_factor is 1.0, return original audio if stretch_factor == 1.0: - return audio_to_comfy_3d(audio['waveform'], audio['sample_rate']) + return audio_to_comfy_3d(audio["waveform"], audio["sample_rate"]) # Extract waveform and sample_rate - waveform, sample_rate = audio_from_comfy_2d(audio, repeat=True,try_gpu=True) + waveform, sample_rate = audio_from_comfy_2d(audio, repeat=True, try_gpu=True) loudness = get_loudness(waveform, sample_rate) nchannels, nsamples = waveform.shape @@ -69,7 +77,9 @@ class SignalProcessingPaulStretch: end_size = int(sample_rate * 0.05) if end_size < 16: end_size = 16 - fade_out = torch.linspace(1.0, 0.0, end_size, device=waveform.device, dtype=waveform.dtype) + fade_out = torch.linspace( + 1.0, 0.0, end_size, device=waveform.device, dtype=waveform.dtype + ) waveform[:, -end_size:] = waveform[:, -end_size:] * fade_out # Compute displacement @@ -77,10 +87,21 @@ class SignalProcessingPaulStretch: displace_pos = (window_size * 0.5) / stretch_factor # Create custom window function as in original code - window = torch.pow(1.0 - torch.pow(torch.linspace(-1.0, 1.0, window_size, device=waveform.device, dtype=waveform.dtype), 2.0), 1.25) + window = torch.pow( + 1.0 + - torch.pow( + torch.linspace( + -1.0, 1.0, window_size, device=waveform.device, dtype=waveform.dtype + ), + 2.0, + ), + 1.25, + ) # Initialize old windowed buffer - old_windowed_buf = torch.zeros((nchannels, window_size), device=waveform.device, dtype=waveform.dtype) + old_windowed_buf = torch.zeros( + (nchannels, window_size), device=waveform.device, dtype=waveform.dtype + ) # Initialize list to store output frames output_frames = [] @@ -90,7 +111,7 @@ class SignalProcessingPaulStretch: while True: # Get the windowed buffer istart_pos = int(math.floor(start_pos)) - buf = waveform[:, istart_pos:istart_pos + window_size] + buf = waveform[:, istart_pos : istart_pos + window_size] if buf.shape[1] < window_size: padding = window_size - buf.shape[1] buf = torch.nn.functional.pad(buf, (0, padding), "constant", 0.0) @@ -101,7 +122,11 @@ class SignalProcessingPaulStretch: # Get amplitudes and randomize phases amplitudes = freqs.abs() - phases = torch.rand(freqs.shape, device=waveform.device, dtype=waveform.dtype) * 2 * math.pi + phases = ( + torch.rand(freqs.shape, device=waveform.device, dtype=waveform.dtype) + * 2 + * math.pi + ) freqs = amplitudes * torch.exp(1j * phases) # Inverse FFT @@ -111,7 +136,9 @@ class SignalProcessingPaulStretch: buf_ifft = buf_ifft * window # Overlap-add the output - output = buf_ifft[:, :half_window_size] + old_windowed_buf[:, half_window_size:] + output = ( + buf_ifft[:, :half_window_size] + old_windowed_buf[:, half_window_size:] + ) old_windowed_buf = buf_ifft # Append to output_frames @@ -163,35 +190,36 @@ if __name__ == "__main__": node = SignalProcessingPaulStretch() types = node.INPUT_TYPES() - samples_path = Path('ComfyUI_SignalProcessing/audio/samples') + samples_path = Path("ComfyUI_SignalProcessing/audio/samples") - samples = list(samples_path.rglob('*.*')) + samples = list(samples_path.rglob("*.*")) print(samples) source_path = samples[1].absolute() - source_audio,source_audio_sample_rate = from_disk_as_raw_2d(source_path) + source_audio, source_audio_sample_rate = from_disk_as_raw_2d(source_path) - input = audio_to_comfy_3d(source_audio,source_audio_sample_rate)[0] + input = audio_to_comfy_3d(source_audio, source_audio_sample_rate)[0] + window_size_seconds = 0.25 + stretch_factor = 2.0 - window_size_seconds=0.25 - stretch_factor=2.0 - - result = node.process(input,stretch_factor=stretch_factor, window_size_seconds=window_size_seconds)[0] + result = node.process( + input, stretch_factor=stretch_factor, window_size_seconds=window_size_seconds + )[0] output_audio, sample_rate_audio = audio_from_comfy_2d(result) - combined = combine_audio_files( source_audio.cpu(), - output_audio.cpu(), - sample_rate_audio, - chunk_duration=4.0 - ) - - torchaudio.save('ComfyUI_SignalProcessing/audio/tests/paulstretch.wav',combined.cpu(),sample_rate_audio) - - #set console to comfy ComfyUI-0.2.4/custom_nodes and run below command - #export coffy_local_dev=1 - #python3 -m ComfyUI_SignalProcessing.effects.SignalProcessingPitchShifter + combined = combine_audio_files( + source_audio.cpu(), output_audio.cpu(), sample_rate_audio, chunk_duration=4.0 + ) + torchaudio.save( + "ComfyUI_SignalProcessing/audio/tests/paulstretch.wav", + combined.cpu(), + sample_rate_audio, + ) + # set console to comfy ComfyUI-0.2.4/custom_nodes and run below command + # export coffy_local_dev=1 + # python3 -m ComfyUI_SignalProcessing.effects.SignalProcessingPitchShifter diff --git a/effects/SignalProcessingPitchShifter.py b/effects/SignalProcessingPitchShifter.py index ac8647c..6a3d895 100644 --- a/effects/SignalProcessingPitchShifter.py +++ b/effects/SignalProcessingPitchShifter.py @@ -15,7 +15,8 @@ from typing import Tuple, Dict import torchaudio.functional as F from ..core.utilities import comfy_root_to_syspath -comfy_root_to_syspath() # add comfy to sys path for dev + +comfy_root_to_syspath() # add comfy to sys path for dev from ..core.io import audio_from_comfy_3d, audio_to_comfy_3d from ..core.loudness import lufs_normalization, get_loudness @@ -27,7 +28,10 @@ class SignalProcessingPitchShifter: return { "required": { "input_audio": ("AUDIO",), # Input audio - "pitch_shift_factor": ("INT", {"default": 2, "min": -12*4, "max": 12*4, "step": 1}), + "pitch_shift_factor": ( + "INT", + {"default": 2, "min": -12 * 4, "max": 12 * 4, "step": 1}, + ), }, "optional": {}, } @@ -43,15 +47,19 @@ class SignalProcessingPitchShifter: pitch_shift_factor: int = 2, ) -> Tuple[Dict[str, torch.Tensor]]: - try_gpu : bool = True - waveform, sample_rate = audio_from_comfy_3d(input_audio,try_gpu=try_gpu) + try_gpu: bool = True + waveform, sample_rate = audio_from_comfy_3d(input_audio, try_gpu=try_gpu) - loudness = get_loudness(waveform,sample_rate) + loudness = get_loudness(waveform, sample_rate) - pitch_shifted_waveform = F.pitch_shift(waveform,sample_rate,pitch_shift_factor) - pitch_shifted_waveform = lufs_normalization(pitch_shifted_waveform,sample_rate,loudness) + pitch_shifted_waveform = F.pitch_shift( + waveform, sample_rate, pitch_shift_factor + ) + pitch_shifted_waveform = lufs_normalization( + pitch_shifted_waveform, sample_rate, loudness + ) - return audio_to_comfy_3d(pitch_shifted_waveform,sample_rate) + return audio_to_comfy_3d(pitch_shifted_waveform, sample_rate) if __name__ == "__main__": @@ -64,24 +72,26 @@ if __name__ == "__main__": node = SignalProcessingPitchShifter() types = node.INPUT_TYPES() - samples_path = Path('ComfyUI_SignalProcessing/audio/samples') + samples_path = Path("ComfyUI_SignalProcessing/audio/samples") - samples = list(samples_path.rglob('*.*')) + samples = list(samples_path.rglob("*.*")) source_path = samples[1].absolute() - source_audio,source_audio_sample_rate = from_disk_as_raw_2d(source_path) + source_audio, source_audio_sample_rate = from_disk_as_raw_2d(source_path) - input = audio_to_comfy_3d(source_audio,source_audio_sample_rate)[0] + input = audio_to_comfy_3d(source_audio, source_audio_sample_rate)[0] - pitch_shift_factor=-4 + pitch_shift_factor = -4 - result = node.process(input,pitch_shift_factor=pitch_shift_factor)[0] + result = node.process(input, pitch_shift_factor=pitch_shift_factor)[0] output_audio, sample_rate_audio = audio_from_comfy_2d(result) - combined = combine_audio_files( source_audio.cpu(), - output_audio.cpu(), - sample_rate_audio, - chunk_duration=4.0 - ) - torchaudio.save('ComfyUI_SignalProcessing/audio/tests/pitchshifter.wav',combined.cpu(),sample_rate_audio) \ No newline at end of file + combined = combine_audio_files( + source_audio.cpu(), output_audio.cpu(), sample_rate_audio, chunk_duration=4.0 + ) + torchaudio.save( + "ComfyUI_SignalProcessing/audio/tests/pitchshifter.wav", + combined.cpu(), + sample_rate_audio, + ) diff --git a/effects/SignalProcessingStereoWidening.py b/effects/SignalProcessingStereoWidening.py index 13f81ac..cda25d6 100644 --- a/effects/SignalProcessingStereoWidening.py +++ b/effects/SignalProcessingStereoWidening.py @@ -19,24 +19,33 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "co from ..core.io import audio_from_comfy_2d, audio_to_comfy_3d from ..core.loudness import lufs_normalization, get_loudness -from ..core.widening import StereoWidenerFrequencyBased,DecorrelationType,FilterbankType +from ..core.widening import ( + StereoWidenerFrequencyBased, + DecorrelationType, + FilterbankType, +) + def interpolate(t, a, b): if not 0.0 <= t <= 1.0: raise ValueError("t must be in the range [0.0, 1.0]") return a + t * (b - a) + class SignalProcessingStereoWidening: @classmethod def INPUT_TYPES(cls): return { "required": { - "mode" : (["decorrelation","simple"],), - "audio_input": ("AUDIO",) + "mode": (["decorrelation", "simple"],), + "audio_input": ("AUDIO",), }, "optional": { - "width": ("FLOAT", {"default": 6.0, "min": 1.0, "max": 8.0, "step": 0.1}), - } + "width": ( + "FLOAT", + {"default": 6.0, "min": 1.0, "max": 8.0, "step": 0.1}, + ), + }, } RETURN_TYPES = ("AUDIO",) @@ -56,15 +65,19 @@ class SignalProcessingStereoWidening: Tuple[Dict[str, torch.Tensor]]: Dictionary with widened 'waveform' and 'sample_rate'. """ - waveform, sample_rate = audio_from_comfy_2d(audio_input,repeat=False,try_gpu=True) + waveform, sample_rate = audio_from_comfy_2d( + audio_input, repeat=False, try_gpu=True + ) channels, num_samples = waveform.shape - loudness = get_loudness(waveform,sample_rate) + loudness = get_loudness(waveform, sample_rate) if mode == "simple": if channels not in [1, 2]: - raise ValueError(f"Unsupported number of channels: {channels}. Only mono and stereo are supported.") + raise ValueError( + f"Unsupported number of channels: {channels}. Only mono and stereo are supported." + ) # Calculate coefficients based on the provided width parameter width_coeff = 1.0 / max(1.0 + width, 2.0) # Scalar @@ -85,7 +98,9 @@ class SignalProcessingStereoWidening: widened_R = mid + sides # New Right channel # Stack the widened channels back into a stereo waveform - widened_waveform = torch.stack((widened_L, widened_R), dim=0) # [2, samples] + widened_waveform = torch.stack( + (widened_L, widened_R), dim=0 + ) # [2, samples] elif channels == 1: # Mono to Wide Stereo @@ -100,11 +115,15 @@ class SignalProcessingStereoWidening: widened_R = mid + sides # New Right channel # Stack the widened channels into a stereo waveform - widened_waveform = torch.stack((widened_L, widened_R), dim=0) # [2, samples] + widened_waveform = torch.stack( + (widened_L, widened_R), dim=0 + ) # [2, samples] - widened_waveform = lufs_normalization(widened_waveform,sample_rate,loudness) + widened_waveform = lufs_normalization( + widened_waveform, sample_rate, loudness + ) - return audio_to_comfy_3d(widened_waveform,sample_rate) + return audio_to_comfy_3d(widened_waveform, sample_rate) if mode == "decorrelation": @@ -113,20 +132,29 @@ class SignalProcessingStereoWidening: decorellation_type = DecorrelationType.VELVET filterbank_type = FilterbankType.ENERGY_PRESERVE start_value = 0.0 - end_value = math.pi/2 + end_value = math.pi / 2 if width > 1.0: width = 1.0 - - beta = interpolate(width, start_value, end_value) - cutoff_frequency_hz = 22000# sample_rate//2 # max possible - cutoff_frequency_hz = (sample_rate//2) - 10 # max possible - stereoWidener = StereoWidenerFrequencyBased(waveform,sample_rate,filterbank_type,decorellation_type,(beta,beta), cutoff_frequency_hz) + beta = interpolate(width, start_value, end_value) + cutoff_frequency_hz = 22000 # sample_rate//2 # max possible + cutoff_frequency_hz = (sample_rate // 2) - 10 # max possible + + stereoWidener = StereoWidenerFrequencyBased( + waveform, + sample_rate, + filterbank_type, + decorellation_type, + (beta, beta), + cutoff_frequency_hz, + ) widened_waveform = torch.from_numpy(stereoWidener.process()) widened_waveform = widened_waveform.T - widened_waveform = lufs_normalization(widened_waveform,sample_rate,loudness) - - return audio_to_comfy_3d(widened_waveform,sample_rate) \ No newline at end of file + widened_waveform = lufs_normalization( + widened_waveform, sample_rate, loudness + ) + + return audio_to_comfy_3d(widened_waveform, sample_rate) diff --git a/generators/SignalProcessingPadSynth.py b/generators/SignalProcessingPadSynth.py index 60aad5c..99df412 100644 --- a/generators/SignalProcessingPadSynth.py +++ b/generators/SignalProcessingPadSynth.py @@ -16,15 +16,28 @@ from typing import Tuple, List, Dict from ..core.io import audio_to_comfy_3d + class SignalProcessingPadSynth: @classmethod def INPUT_TYPES(cls) -> Dict: return { "required": { - "sample_rate": ("INT", {"default": 44100, "min": 8000, "max": 96000, "step": 1}), - "fundamental_freq": ("FLOAT", {"default": 261.0, "min": 20.0, "max": 2000.0, "step": 1.0}), - "bandwidth_cents": ("FLOAT", {"default": 40.0, "min": 10.0, "max": 100.0, "step": 1.0}), - "number_harmonics": ("INT", {"default": 64, "min": 1, "max": 128, "step": 1}) + "sample_rate": ( + "INT", + {"default": 44100, "min": 8000, "max": 96000, "step": 1}, + ), + "fundamental_freq": ( + "FLOAT", + {"default": 261.0, "min": 20.0, "max": 2000.0, "step": 1.0}, + ), + "bandwidth_cents": ( + "FLOAT", + {"default": 40.0, "min": 10.0, "max": 100.0, "step": 1.0}, + ), + "number_harmonics": ( + "INT", + {"default": 64, "min": 1, "max": 128, "step": 1}, + ), } } @@ -66,12 +79,14 @@ class SignalProcessingPadSynth: # Initialize frequency amplitude and phase arrays freq_amp = torch.zeros(N // 2, dtype=torch.double) - freq_phase = torch.rand(N // 2, dtype=torch.double) * 2.0 * math.pi # Random phases between 0 and 2pi + freq_phase = ( + torch.rand(N // 2, dtype=torch.double) * 2.0 * math.pi + ) # Random phases between 0 and 2pi # Define Gaussian profile function def profile(fi: torch.Tensor, bwi: torch.Tensor) -> torch.Tensor: x = fi / bwi - x_sq = x ** 2 + x_sq = x**2 # Avoid computing exp(-x^2) for x_sq > 14.71280603 mask = x_sq <= 14.71280603 result = torch.zeros_like(x_sq) @@ -93,7 +108,9 @@ class SignalProcessingPadSynth: # Create tensors for frequency bins i = torch.arange(N // 2, dtype=torch.double) # Normalized frequency for each bin - normalized_freq = i / N # Equivalent to i * (sample_rate / N) / sample_rate = i / N + normalized_freq = ( + i / N + ) # Equivalent to i * (sample_rate / N) / sample_rate = i / N # Compute profile fi_tensor = torch.full_like(i, fi) @@ -123,4 +140,4 @@ class SignalProcessingPadSynth: # Prepare waveform tensor: (C, N) waveform_out = smp.unsqueeze(0) # Mono audio - return audio_to_comfy_3d(waveform_out,sample_rate) \ No newline at end of file + return audio_to_comfy_3d(waveform_out, sample_rate) diff --git a/generators/SignalProcessingPadSynthChoir.py b/generators/SignalProcessingPadSynthChoir.py index 1565c7f..41148b4 100644 --- a/generators/SignalProcessingPadSynthChoir.py +++ b/generators/SignalProcessingPadSynthChoir.py @@ -13,17 +13,30 @@ import torch import math from typing import Tuple, List, Dict + class SignalProcessingPadSynthChoir: @classmethod def INPUT_TYPES(cls) -> Dict: return { "required": { - "samplerate": ("INT", {"default": 44100, "min": 8000, "max": 96000, "step": 1}), - "base_freq": ("FLOAT", {"default": 130.81, "min": 20.0, "max": 2000.0, "step": 1.0}), + "samplerate": ( + "INT", + {"default": 44100, "min": 8000, "max": 96000, "step": 1}, + ), + "base_freq": ( + "FLOAT", + {"default": 130.81, "min": 20.0, "max": 2000.0, "step": 1.0}, + ), "step_size": ("INT", {"default": 4, "min": 1, "max": 24, "step": 1}), "num_notes": ("INT", {"default": 7, "min": 1, "max": 24, "step": 1}), - "bandwidth_cents": ("FLOAT", {"default": 60.0, "min": 10.0, "max": 100.0, "step": 1.0}), - "number_harmonics": ("INT", {"default": 64, "min": 1, "max": 128, "step": 1}) + "bandwidth_cents": ( + "FLOAT", + {"default": 60.0, "min": 10.0, "max": 100.0, "step": 1.0}, + ), + "number_harmonics": ( + "INT", + {"default": 64, "min": 1, "max": 128, "step": 1}, + ), } } @@ -72,11 +85,11 @@ class SignalProcessingPadSynthChoir: for i in range(1, number_harmonics): # Calculate formants based on the C++ choir implementation formants = ( - math.exp(-((i * f1 - 600.0) / 150.0) ** 2) + - math.exp(-((i * f1 - 900.0) / 250.0) ** 2) + - math.exp(-((i * f1 - 2200.0) / 200.0) ** 2) + - math.exp(-((i * f1 - 2600.0) / 250.0) ** 2) + - math.exp(-((i * f1) / 3000.0) ** 2) * 0.1 + math.exp(-(((i * f1 - 600.0) / 150.0) ** 2)) + + math.exp(-(((i * f1 - 900.0) / 250.0) ** 2)) + + math.exp(-(((i * f1 - 2200.0) / 200.0) ** 2)) + + math.exp(-(((i * f1 - 2600.0) / 250.0) ** 2)) + + math.exp(-(((i * f1) / 3000.0) ** 2)) * 0.1 ) A[i] = (1.0 / i) * formants # Optionally, you can debug amplitude values @@ -84,12 +97,14 @@ class SignalProcessingPadSynthChoir: # Initialize frequency amplitude and phase arrays freq_amp = torch.zeros(N // 2, dtype=torch.double) - freq_phase = torch.rand(N // 2, dtype=torch.double) * 2.0 * math.pi # Random phases between 0 and 2pi + freq_phase = ( + torch.rand(N // 2, dtype=torch.double) * 2.0 * math.pi + ) # Random phases between 0 and 2pi # Define Gaussian profile function def profile(fi: torch.Tensor, bwi: torch.Tensor) -> torch.Tensor: x = fi / bwi - x_sq = x ** 2 + x_sq = x**2 # Avoid computing exp(-x^2) for x_sq > 14.71280603 mask = x_sq <= 14.71280603 result = torch.zeros_like(x_sq) @@ -130,7 +145,9 @@ class SignalProcessingPadSynthChoir: max_val = torch.max(torch.abs(smp)) if max_val < 1e-5: max_val = 1e-5 # Prevent division by zero - smp = smp / (max_val * math.sqrt(2)) # Normalize to 1/sqrt(2) as in C++ code + smp = smp / ( + max_val * math.sqrt(2) + ) # Normalize to 1/sqrt(2) as in C++ code # Convert to float32 for saving smp = smp.float() @@ -142,8 +159,8 @@ class SignalProcessingPadSynthChoir: waveform_out = waveform_out.unsqueeze(0) # Shape: (1, C, N) # Append to audios list - audios.append({'waveform':waveform_out,'sample_rate': samplerate}) + audios.append({"waveform": waveform_out, "sample_rate": samplerate}) # Return the list of generated audios - return audios, samplerate \ No newline at end of file + return audios, samplerate diff --git a/nodes.py b/nodes.py index f68ee8e..f35a4c1 100644 --- a/nodes.py +++ b/nodes.py @@ -12,22 +12,29 @@ Description: # generators from .generators.SignalProcessingPadSynth import SignalProcessingPadSynth from .generators.SignalProcessingPadSynthChoir import SignalProcessingPadSynthChoir -# effects + +# effects from .effects.SignalProcessingStereoWidening import SignalProcessingStereoWidening from .effects.SignalProcessingPaulStretch import SignalProcessingPaulStretch from .effects.SignalProcessingPitchShifter import SignalProcessingPitchShifter from .effects.SignalProcessingConvolutionReverb import SignalProcessingConvolutionReverb + # processors from .processors.SignalProcessingFilter import SignalProcessingFilter from .processors.SignalProcessingMixdown import SignalProcessingMixdown from .processors.SignalProcessingLoadAudio import SignalProcessingLoadAudio from .processors.SignalProcessingNormalizer import SignalProcessingNormalizer from .processors.SignalProcessingLoudness import SignalProcessingLoudness -from .processors.SignalProcessingBaxandallEQ import SignalProcessingBaxandallEQ,SignalProcessingBaxandall3BandEQ +from .processors.SignalProcessingBaxandallEQ import ( + SignalProcessingBaxandallEQ, + SignalProcessingBaxandall3BandEQ, +) +from .processors.SignalProcessingHarmonicsEnhancer import SignalProcessingHarmonicsEnhancer + # visuals from .visuals.SignalProcessingSpectrogram import SignalProcessingSpectrogram from .visuals.SignalProcessingWaveform import SignalProcessingWaveform - + NODE_CLASS_MAPPINGS = { "SignalProcessingLoadAudio": SignalProcessingLoadAudio, "SignalProcessingFilter": SignalProcessingFilter, @@ -35,31 +42,33 @@ NODE_CLASS_MAPPINGS = { "SignalProcessingPadSynth": SignalProcessingPadSynth, "SignalProcessingPadSynthChoir": SignalProcessingPadSynthChoir, "SignalProcessingMixdown": SignalProcessingMixdown, - "SignalProcessingSpectrogram" : SignalProcessingSpectrogram, - "SignalProcessingWaveform" : SignalProcessingWaveform, - "SignalProcessingStereoWidening" : SignalProcessingStereoWidening, - "SignalProcessingPitchShifter":SignalProcessingPitchShifter, + "SignalProcessingSpectrogram": SignalProcessingSpectrogram, + "SignalProcessingWaveform": SignalProcessingWaveform, + "SignalProcessingStereoWidening": SignalProcessingStereoWidening, + "SignalProcessingPitchShifter": SignalProcessingPitchShifter, "SignalProcessingConvolutionReverb": SignalProcessingConvolutionReverb, - "SignalProcessingNormalizer" : SignalProcessingNormalizer, - "SignalProcessingLoudness" : SignalProcessingLoudness, - "SignalProcessingBaxandallEQ" : SignalProcessingBaxandallEQ, - "SignalProcessingBaxandall3BandEQ" : SignalProcessingBaxandall3BandEQ + "SignalProcessingNormalizer": SignalProcessingNormalizer, + "SignalProcessingLoudness": SignalProcessingLoudness, + "SignalProcessingBaxandallEQ": SignalProcessingBaxandallEQ, + "SignalProcessingBaxandall3BandEQ": SignalProcessingBaxandall3BandEQ, + "SignalProcessingHarmonicsEnhancer" : SignalProcessingHarmonicsEnhancer } NODE_DISPLAY_NAME_MAPPINGS = { "SignalProcessingLoadAudio": "(SP) Load Audio", "SignalProcessingFilter": "(SP) Filter", - "SignalProcessingPaulStretch" : "(SP) PaulStretch", + "SignalProcessingPaulStretch": "(SP) PaulStretch", "SignalProcessingPadSynth": "(SP) PadSynth", "SignalProcessingPadSynthChoir": "(SP) PadSynth Choir", "SignalProcessingMixdown": "(SP) Mix Down", - "SignalProcessingSpectrogram" : "(SP) Spectogram", - "SignalProcessingWaveform" : "(SP) Waveform", - "SignalProcessingStereoWidening" : "(SP) Stereo Width", + "SignalProcessingSpectrogram": "(SP) Spectogram", + "SignalProcessingWaveform": "(SP) Waveform", + "SignalProcessingStereoWidening": "(SP) Stereo Width", "SignalProcessingPitchShifter": "(SP) PitchShift", - "SignalProcessingConvolutionReverb" : "(SP) Convolution Reverb", - "SignalProcessingNormalizer" : "(SP) Normalizer", - "SignalProcessingLoudness" : "(SP) Loudness", - "SignalProcessingBaxandallEQ" : "(SP) Baxandall EQ", - "SignalProcessingBaxandall3BandEQ" : "(SP) Baxandall 3 Band EQ" + "SignalProcessingConvolutionReverb": "(SP) Convolution Reverb", + "SignalProcessingNormalizer": "(SP) Normalizer", + "SignalProcessingLoudness": "(SP) Loudness", + "SignalProcessingBaxandallEQ": "(SP) Baxandall EQ", + "SignalProcessingBaxandall3BandEQ": "(SP) Baxandall 3 Band EQ", + "SignalProcessingHarmonicsEnhancer" : "(SP) Enhance Harmonics" } diff --git a/processors/SignalProcessingBaxandallEQ.py b/processors/SignalProcessingBaxandallEQ.py index e5a1b1b..52576ea 100644 --- a/processors/SignalProcessingBaxandallEQ.py +++ b/processors/SignalProcessingBaxandallEQ.py @@ -20,14 +20,21 @@ from ..core.loudness import lufs_normalization, get_loudness import torch import math + class SignalProcessingBaxandallEQ: @classmethod def INPUT_TYPES(cls): return { "required": { "audio_input": ("AUDIO",), - "bass_gain_db": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}), - "treble_gain_db": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}), + "bass_gain_db": ( + "FLOAT", + {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}, + ), + "treble_gain_db": ( + "FLOAT", + {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}, + ), }, } @@ -41,55 +48,93 @@ class SignalProcessingBaxandallEQ: loudness = get_loudness(waveform, sample_rate) # Apply Bass Shelf (low shelf) using RBJ formula - b_bass, a_bass = self.design_rbj_shelf(sample_rate, freq=100.0, gain_db=bass_gain_db, shelf_type='low') - waveform = torchaudio.functional.lfilter(waveform, a_bass.to(waveform.device), b_bass.to(waveform.device),clamp=False) + b_bass, a_bass = self.design_rbj_shelf( + sample_rate, freq=100.0, gain_db=bass_gain_db, shelf_type="low" + ) + waveform = torchaudio.functional.lfilter( + waveform, + a_bass.to(waveform.device), + b_bass.to(waveform.device), + clamp=False, + ) # Apply Treble Shelf (high shelf) using RBJ formula - b_treble, a_treble = self.design_rbj_shelf(sample_rate, freq=10000.0, gain_db=treble_gain_db, shelf_type='high') - waveform = torchaudio.functional.lfilter(waveform, a_treble.to(waveform.device), b_treble.to(waveform.device),clamp=False) + b_treble, a_treble = self.design_rbj_shelf( + sample_rate, freq=10000.0, gain_db=treble_gain_db, shelf_type="high" + ) + waveform = torchaudio.functional.lfilter( + waveform, + a_treble.to(waveform.device), + b_treble.to(waveform.device), + clamp=False, + ) waveform = lufs_normalization(waveform, sample_rate, loudness) return audio_to_comfy_3d(waveform, sample_rate) - def design_rbj_shelf(self, sr, freq, gain_db, shelf_type='low'): + def design_rbj_shelf(self, sr, freq, gain_db, shelf_type="low"): # RBJ Audio EQ Cookbook shelf filters - A = 10.0**(gain_db/40.0) - w0 = 2*math.pi*freq/sr - alpha = math.sin(w0)/2.0 * math.sqrt((A + 1/A)*(1.0/1.0 - 1) + 2.0) # S=1.0 + A = 10.0 ** (gain_db / 40.0) + w0 = 2 * math.pi * freq / sr + alpha = ( + math.sin(w0) / 2.0 * math.sqrt((A + 1 / A) * (1.0 / 1.0 - 1) + 2.0) + ) # S=1.0 cosw0 = math.cos(w0) - if shelf_type == 'low': - b0 = A*((A+1) - (A-1)*cosw0 + 2*math.sqrt(A)*alpha) - b1 = 2*A*((A-1) - (A+1)*cosw0) - b2 = A*((A+1) - (A-1)*cosw0 - 2*math.sqrt(A)*alpha) - a0 = (A+1) + (A-1)*cosw0 + 2*math.sqrt(A)*alpha - a1 = -2*((A-1) + (A+1)*cosw0) - a2 = (A+1) + (A-1)*cosw0 - 2*math.sqrt(A)*alpha + if shelf_type == "low": + b0 = A * ((A + 1) - (A - 1) * cosw0 + 2 * math.sqrt(A) * alpha) + b1 = 2 * A * ((A - 1) - (A + 1) * cosw0) + b2 = A * ((A + 1) - (A - 1) * cosw0 - 2 * math.sqrt(A) * alpha) + a0 = (A + 1) + (A - 1) * cosw0 + 2 * math.sqrt(A) * alpha + a1 = -2 * ((A - 1) + (A + 1) * cosw0) + a2 = (A + 1) + (A - 1) * cosw0 - 2 * math.sqrt(A) * alpha else: # high shelf - b0 = A*((A+1) + (A-1)*cosw0 + 2*math.sqrt(A)*alpha) - b1 = -2*A*((A-1) + (A+1)*cosw0) - b2 = A*((A+1) + (A-1)*cosw0 - 2*math.sqrt(A)*alpha) - a0 = (A+1) - (A-1)*cosw0 + 2*math.sqrt(A)*alpha - a1 = 2*((A-1) - (A+1)*cosw0) - a2 = (A+1) - (A-1)*cosw0 - 2*math.sqrt(A)*alpha + b0 = A * ((A + 1) + (A - 1) * cosw0 + 2 * math.sqrt(A) * alpha) + b1 = -2 * A * ((A - 1) + (A + 1) * cosw0) + b2 = A * ((A + 1) + (A - 1) * cosw0 - 2 * math.sqrt(A) * alpha) + a0 = (A + 1) - (A - 1) * cosw0 + 2 * math.sqrt(A) * alpha + a1 = 2 * ((A - 1) - (A + 1) * cosw0) + a2 = (A + 1) - (A - 1) * cosw0 - 2 * math.sqrt(A) * alpha - b = torch.tensor([b0/a0, b1/a0, b2/a0], dtype=torch.float64) - a = torch.tensor([1.0, a1/a0, a2/a0], dtype=torch.float64) + b = torch.tensor([b0 / a0, b1 / a0, b2 / a0], dtype=torch.float64) + a = torch.tensor([1.0, a1 / a0, a2 / a0], dtype=torch.float64) return b, a + class SignalProcessingBaxandall3BandEQ: @classmethod def INPUT_TYPES(cls): return { "required": { "audio_input": ("AUDIO",), - "bass_gain_db": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}), - "mid_gain_db": ("FLOAT", {"default": 0.0, "min": -20.0, "max": 20.0, "step": 0.1}), - "treble_gain_db": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}), - "low_freq": ("FLOAT", {"default": 100.0, "min": 20.0, "max": 500.0, "step": 1.0}), - "mid_freq": ("FLOAT", {"default": 1000.0, "min": 200.0, "max": 5000.0, "step": 10.0}), - "high_freq": ("FLOAT", {"default": 10000.0, "min": 2000.0, "max": 20000.0, "step": 100.0}), - "mid_q": ("FLOAT", {"default": 0.7, "min": 0.1, "max": 10.0, "step": 0.1}), + "bass_gain_db": ( + "FLOAT", + {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}, + ), + "mid_gain_db": ( + "FLOAT", + {"default": 0.0, "min": -20.0, "max": 20.0, "step": 0.1}, + ), + "treble_gain_db": ( + "FLOAT", + {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.1}, + ), + "low_freq": ( + "FLOAT", + {"default": 100.0, "min": 20.0, "max": 500.0, "step": 1.0}, + ), + "mid_freq": ( + "FLOAT", + {"default": 1000.0, "min": 200.0, "max": 5000.0, "step": 10.0}, + ), + "high_freq": ( + "FLOAT", + {"default": 10000.0, "min": 2000.0, "max": 20000.0, "step": 100.0}, + ), + "mid_q": ( + "FLOAT", + {"default": 0.7, "min": 0.1, "max": 10.0, "step": 0.1}, + ), }, } @@ -107,7 +152,7 @@ class SignalProcessingBaxandall3BandEQ: low_freq: float = 100.0, mid_freq: float = 1000.0, high_freq: float = 10000.0, - mid_q: float = 0.7 + mid_q: float = 0.7, ): waveform, sample_rate = audio_from_comfy_3d(audio_input, try_gpu=True) @@ -116,75 +161,77 @@ class SignalProcessingBaxandall3BandEQ: loudness = get_loudness(waveform, sample_rate) # Low shelf filter - b_low, a_low = self.design_rbj_shelf(sample_rate, low_freq, bass_gain_db, shelf_type='low') + b_low, a_low = self.design_rbj_shelf( + sample_rate, low_freq, bass_gain_db, shelf_type="low" + ) b_low = b_low.to(device=device, dtype=dtype) a_low = a_low.to(device=device, dtype=dtype) - waveform = torchaudio.functional.lfilter(waveform, a_low, b_low,clamp=False) + waveform = torchaudio.functional.lfilter(waveform, a_low, b_low, clamp=False) # Mid peaking filter b_mid, a_mid = self.design_rbj_peak(sample_rate, mid_freq, mid_gain_db, Q=mid_q) b_mid = b_mid.to(device=device, dtype=dtype) a_mid = a_mid.to(device=device, dtype=dtype) - waveform = torchaudio.functional.lfilter(waveform, a_mid, b_mid,clamp=False) + waveform = torchaudio.functional.lfilter(waveform, a_mid, b_mid, clamp=False) # High shelf filter - b_high, a_high = self.design_rbj_shelf(sample_rate, high_freq, treble_gain_db, shelf_type='high') + b_high, a_high = self.design_rbj_shelf( + sample_rate, high_freq, treble_gain_db, shelf_type="high" + ) b_high = b_high.to(device=device, dtype=dtype) a_high = a_high.to(device=device, dtype=dtype) - waveform = torchaudio.functional.lfilter(waveform, a_high, b_high,clamp=False) + waveform = torchaudio.functional.lfilter(waveform, a_high, b_high, clamp=False) # Normalize loudness after EQ waveform = lufs_normalization(waveform, sample_rate, loudness) return audio_to_comfy_3d(waveform, sample_rate) - - def design_rbj_shelf(self, sr, freq, gain_db, shelf_type='low'): + def design_rbj_shelf(self, sr, freq, gain_db, shelf_type="low"): # RBJ audio EQ cookbook formula for shelving filters - A = 10.0**(gain_db/40.0) - w0 = 2.0*math.pi*freq/sr + A = 10.0 ** (gain_db / 40.0) + w0 = 2.0 * math.pi * freq / sr # Slope S=1.0 (Baxandall-like gentle slope) S = 1.0 - alpha = math.sin(w0)/2.0 * math.sqrt((A + 1.0/A)*(1.0/S - 1.0) + 2.0) + alpha = math.sin(w0) / 2.0 * math.sqrt((A + 1.0 / A) * (1.0 / S - 1.0) + 2.0) cosw0 = math.cos(w0) - if shelf_type == 'low': - b0 = A*((A+1.0)-(A-1.0)*cosw0+2.0*math.sqrt(A)*alpha) - b1 = 2.0*A*((A-1.0)-(A+1.0)*cosw0) - b2 = A*((A+1.0)-(A-1.0)*cosw0-2.0*math.sqrt(A)*alpha) - a0 = (A+1.0)+(A-1.0)*cosw0+2.0*math.sqrt(A)*alpha - a1 = -2.0*((A-1.0)+(A+1.0)*cosw0) - a2 = (A+1.0)+(A-1.0)*cosw0-2.0*math.sqrt(A)*alpha + if shelf_type == "low": + b0 = A * ((A + 1.0) - (A - 1.0) * cosw0 + 2.0 * math.sqrt(A) * alpha) + b1 = 2.0 * A * ((A - 1.0) - (A + 1.0) * cosw0) + b2 = A * ((A + 1.0) - (A - 1.0) * cosw0 - 2.0 * math.sqrt(A) * alpha) + a0 = (A + 1.0) + (A - 1.0) * cosw0 + 2.0 * math.sqrt(A) * alpha + a1 = -2.0 * ((A - 1.0) + (A + 1.0) * cosw0) + a2 = (A + 1.0) + (A - 1.0) * cosw0 - 2.0 * math.sqrt(A) * alpha else: # high shelf - b0 = A*((A+1.0)+(A-1.0)*cosw0+2.0*math.sqrt(A)*alpha) - b1 = -2.0*A*((A-1.0)+(A+1.0)*cosw0) - b2 = A*((A+1.0)+(A-1.0)*cosw0-2.0*math.sqrt(A)*alpha) - a0 = (A+1.0)-(A-1.0)*cosw0+2.0*math.sqrt(A)*alpha - a1 = 2.0*((A-1.0)-(A+1.0)*cosw0) - a2 = (A+1.0)-(A-1.0)*cosw0-2.0*math.sqrt(A)*alpha + b0 = A * ((A + 1.0) + (A - 1.0) * cosw0 + 2.0 * math.sqrt(A) * alpha) + b1 = -2.0 * A * ((A - 1.0) + (A + 1.0) * cosw0) + b2 = A * ((A + 1.0) + (A - 1.0) * cosw0 - 2.0 * math.sqrt(A) * alpha) + a0 = (A + 1.0) - (A - 1.0) * cosw0 + 2.0 * math.sqrt(A) * alpha + a1 = 2.0 * ((A - 1.0) - (A + 1.0) * cosw0) + a2 = (A + 1.0) - (A - 1.0) * cosw0 - 2.0 * math.sqrt(A) * alpha - b = torch.tensor([b0/a0, b1/a0, b2/a0], dtype=torch.float64) - a = torch.tensor([1.0, a1/a0, a2/a0], dtype=torch.float64) + b = torch.tensor([b0 / a0, b1 / a0, b2 / a0], dtype=torch.float64) + a = torch.tensor([1.0, a1 / a0, a2 / a0], dtype=torch.float64) return b, a - def design_rbj_peak(self, sr, freq, gain_db, Q=0.7): # RBJ audio EQ cookbook peak filter - A = 10.0**(gain_db/40.0) - w0 = 2.0*math.pi*freq/sr - alpha = math.sin(w0)/(2.0*Q) + A = 10.0 ** (gain_db / 40.0) + w0 = 2.0 * math.pi * freq / sr + alpha = math.sin(w0) / (2.0 * Q) cosw0 = math.cos(w0) - b0 = 1.0 + alpha*A - b1 = -2.0*cosw0 - b2 = 1.0 - alpha*A - a0 = 1.0 + alpha/A - a1 = -2.0*cosw0 - a2 = 1.0 - alpha/A + b0 = 1.0 + alpha * A + b1 = -2.0 * cosw0 + b2 = 1.0 - alpha * A + a0 = 1.0 + alpha / A + a1 = -2.0 * cosw0 + a2 = 1.0 - alpha / A - b = torch.tensor([b0/a0, b1/a0, b2/a0], dtype=torch.float64) - a = torch.tensor([1.0, a1/a0, a2/a0], dtype=torch.float64) + b = torch.tensor([b0 / a0, b1 / a0, b2 / a0], dtype=torch.float64) + a = torch.tensor([1.0, a1 / a0, a2 / a0], dtype=torch.float64) return b, a @@ -192,9 +239,9 @@ if __name__ == "__main__": import torchaudio from pathlib import Path from ..core.io import from_disk_as_raw_2d, audio_to_comfy_3d, audio_from_comfy_2d - + node = SignalProcessingBaxandallEQ() - samples_path = Path('ComfyUI_SignalProcessing/audio/inputs/song.mp4') + samples_path = Path("ComfyUI_SignalProcessing/audio/inputs/song.mp4") source_path = samples_path.absolute() source_audio, source_audio_sample_rate = from_disk_as_raw_2d(source_path) @@ -206,19 +253,35 @@ if __name__ == "__main__": output_audio, sample_rate_audio = audio_from_comfy_2d(result) # Save output for analysis - torchaudio.save('ComfyUI_SignalProcessing/audio/tests/baxandall_eq.wav', output_audio.cpu(), sample_rate_audio) - + torchaudio.save( + "ComfyUI_SignalProcessing/audio/tests/baxandall_eq.wav", + output_audio.cpu(), + sample_rate_audio, + ) node = SignalProcessingBaxandall3BandEQ() # Example usage: # Provide a test audio file path - test_audio_path = Path('ComfyUI_SignalProcessing/audio/samples/test_audio.wav') + test_audio_path = Path("ComfyUI_SignalProcessing/audio/samples/test_audio.wav") source_audio, source_audio_sample_rate = from_disk_as_raw_2d(test_audio_path) input_tensors = audio_to_comfy_3d(source_audio, source_audio_sample_rate)[0] # Apply EQ with some settings: - result = node.process(input_tensors, bass_gain_db=4.0, mid_gain_db=-2.0, treble_gain_db=3.0, low_freq=100, mid_freq=1000, high_freq=10000, mid_q=0.7)[0] + result = node.process( + input_tensors, + bass_gain_db=4.0, + mid_gain_db=-2.0, + treble_gain_db=3.0, + low_freq=100, + mid_freq=1000, + high_freq=10000, + mid_q=0.7, + )[0] output_audio, out_sr = audio_from_comfy_2d(result) - torchaudio.save('ComfyUI_SignalProcessing/audio/tests/3band_baxandall_eq_output.wav', output_audio.cpu(), out_sr) + torchaudio.save( + "ComfyUI_SignalProcessing/audio/tests/3band_baxandall_eq_output.wav", + output_audio.cpu(), + out_sr, + ) diff --git a/processors/SignalProcessingFilter.py b/processors/SignalProcessingFilter.py index 9878d09..148d710 100644 --- a/processors/SignalProcessingFilter.py +++ b/processors/SignalProcessingFilter.py @@ -23,18 +23,33 @@ class SignalProcessingFilter: return { "required": { "audio": ("AUDIO", {"forceInput": True}), - "cutoff": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), - "filter_type": (["lowpass", "highpass", "bandpass", "bandstop"], {"default": "lowpass"}), - "q_factor": ("FLOAT", {"default": 0.707, "min": 0.1, "max": 5.0, "step": 0.01}), # For resonance/bandwidth + "cutoff": ( + "FLOAT", + {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}, + ), + "filter_type": ( + ["lowpass", "highpass", "bandpass", "bandstop"], + {"default": "lowpass"}, + ), + "q_factor": ( + "FLOAT", + {"default": 0.707, "min": 0.1, "max": 5.0, "step": 0.01}, + ), # For resonance/bandwidth } } - RETURN_TYPES = ("AUDIO","INT") - RETURN_NAMES = ("audio","sample_rate") + RETURN_TYPES = ("AUDIO", "INT") + RETURN_NAMES = ("audio", "sample_rate") CATEGORY = "Signal Processing" FUNCTION = "apply_filter" - def apply_filter(self, audio: Dict[str, torch.Tensor], cutoff: float, filter_type: str, q_factor: float): + def apply_filter( + self, + audio: Dict[str, torch.Tensor], + cutoff: float, + filter_type: str, + q_factor: float, + ): """ Apply a specified filter to the input audio. @@ -50,12 +65,12 @@ class SignalProcessingFilter: waveform, sample_rate = audio_from_comfy_3d(audio) - loudness = get_loudness(waveform,sample_rate) + loudness = get_loudness(waveform, sample_rate) nyquist = sample_rate / 2.0 # Define minimum and maximum frequencies for mapping - log_min = 20.0 # 20 Hz, typical lower bound of human hearing + log_min = 20.0 # 20 Hz, typical lower bound of human hearing log_max = nyquist - 100.0 # Slightly below Nyquist to prevent instability # Avoid log(0) by ensuring cutoff is within (0,1) @@ -67,7 +82,6 @@ class SignalProcessingFilter: log_cutoff = log_min + cutoff * (log_max - log_min) cutoff_freq = torch.exp(log_cutoff).item() - # Choose filter type if filter_type == "lowpass": filtered_waveform = torchaudio.functional.lowpass_biquad( @@ -81,8 +95,12 @@ class SignalProcessingFilter: center_freq = cutoff_freq # Ensure that the bandwidth does not exceed the Nyquist frequency bandwidth = center_freq / q_factor - lower_freq = max(center_freq - bandwidth / 2.0, 20.0) # Prevent dropping below 20 Hz - upper_freq = min(center_freq + bandwidth / 2.0, nyquist - 100.0) # Prevent exceeding Nyquist + lower_freq = max( + center_freq - bandwidth / 2.0, 20.0 + ) # Prevent dropping below 20 Hz + upper_freq = min( + center_freq + bandwidth / 2.0, nyquist - 100.0 + ) # Prevent exceeding Nyquist if filter_type == "bandpass": filtered_waveform = torchaudio.functional.bandpass_biquad( @@ -95,6 +113,6 @@ class SignalProcessingFilter: else: raise ValueError(f"Unsupported filter type: {filter_type}") - filtered_waveform = lufs_normalization(filtered_waveform,sample_rate,loudness) + filtered_waveform = lufs_normalization(filtered_waveform, sample_rate, loudness) - return audio_to_comfy_3d(filtered_waveform,sample_rate) \ No newline at end of file + return audio_to_comfy_3d(filtered_waveform, sample_rate) diff --git a/processors/SignalProcessingHarmonicsEnhancer.py b/processors/SignalProcessingHarmonicsEnhancer.py new file mode 100644 index 0000000..ce5e398 --- /dev/null +++ b/processors/SignalProcessingHarmonicsEnhancer.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Author: C0ffymachyne +License: GPLv3 +Version: 1.0.0 + +Description: + Classic Audio filter set +""" +from ast import literal_eval +import torch, torchaudio +import torch +from typing import Dict + +from ..core.utilities import comfy_root_to_syspath + +comfy_root_to_syspath() # add comfy to sys path for dev +from ..core.io import from_disk_as_raw_2d, audio_to_comfy_3d, audio_from_comfy_2d +from ..core.loudness import lufs_normalization, get_loudness + + +class SignalProcessingHarmonicsEnhancer: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "audio_input": ("AUDIO",), + "harmonics": ("STRING", {"default": "1,3,5,7,9"}), + "mode": (["detect base frequency", "use base frequency"],), + "base_frequency" : ("FLOAT", {"default" : 440, "min" : 0, "max" : 20000 }), + "gain_db" : ("INT", {"default": 5,"min" : 0, "max" : 50, "step" : 1}), + "Q" : ("FLOAT", {"default" : 0.707, "min" : 0, "max" : 1.0, "step" : 0.01 }), + } + } + + RETURN_TYPES = ("AUDIO",) + RETURN_NAMES = ("audio",) + CATEGORY = "Signal Processing" + FUNCTION = "process" + + def process( + self, + audio_input: Dict[str, torch.Tensor], + harmonics : str = '1,3,5,7,9', + mode : str = "detect base frequency", + base_frequency : int = 440, + gain_db : int = 5, + Q: float = 0.707, + ): + waveform, sample_rate = audio_from_comfy_2d(audio_input,try_gpu=True) + loudness = get_loudness(waveform, sample_rate) + try: + harmonics = [literal_eval(x) for x in harmonics.split(',')] + except: + raise RuntimeWarning("Invalid Harmonics Format. Please delimit integers by a comma ',' like this 1,,3,5,7,9 ") + if mode == "detect base frequency": + filtered_waveform = self.enhance_harmonics(waveform,sample_rate,harmonics=harmonics,gain_db=gain_db,Q=Q) + elif mode == "use base frequency": + filtered_waveform = self.enhance_harmonics(waveform,sample_rate,harmonics=harmonics,gain_db=gain_db,base_frequency=base_frequency,Q=Q) + + filtered_waveform = lufs_normalization(filtered_waveform, sample_rate, loudness) + return audio_to_comfy_3d(filtered_waveform, sample_rate) + + def add_harmonics(self, audio : torch.Tensor, gain=1.2): + # Apply saturation using a tanh curve + harmonic_audio = torch.tanh(audio * gain) + return harmonic_audio + + def detect_fundamental(self,audio, sample_rate): + # Estimate the fundamental frequency using a pitch detection method + pitch = torchaudio.functional.detect_pitch_frequency(audio, sample_rate) + + return pitch + + def detect_fundamental_mean(self,audio, sample_rate): + # Estimate the fundamental frequency using a pitch detection method + pitch = torchaudio.functional.detect_pitch_frequency(audio, sample_rate) + + return pitch.mean().item() + + def enhance_harmonics(self,audio, sample_rate, harmonics=[1,3,5,7,9,11], gain_db=5, base_frequency = None,Q = 0.707): + # Detect the base frequency + if base_frequency == None: + base_frequency = self.detect_fundamental_mean(audio, sample_rate) + if base_frequency <= 0: # Fallback if pitch detection fails + base_frequency = 440 # Use a default base frequency + + # Apply EQ boosts to specific harmonic frequencies + + print('base_frequency',base_frequency) + for harmonic in harmonics: + freq = base_frequency * harmonic + if freq < sample_rate / 2: # Ensure it's within the Nyquist frequency + print('center_freq',freq) + audio = torchaudio.functional.equalizer_biquad(audio, sample_rate, center_freq=freq, gain=gain_db,Q=Q) + + return audio + +if __name__ == "__main__": + import torchaudio + from pathlib import Path + from ..core.io import from_disk_as_raw_2d, audio_to_comfy_3d, audio_from_comfy_2d + + node = SignalProcessingHarmonicsEnhancer() + samples_path = Path("ComfyUI_SignalProcessing/audio/inputs/baxandall-normalizer_00003_.flac") + + source_path = samples_path.absolute() + source_audio, source_audio_sample_rate = from_disk_as_raw_2d(source_path) + input = audio_to_comfy_3d(source_audio, source_audio_sample_rate)[0] + + # Test with some gain settings + result = node.process(input)[0] + + output_audio, sample_rate_audio = audio_from_comfy_2d(result) + + # Save output for analysis + torchaudio.save( + "ComfyUI_SignalProcessing/audio/outputs/harmonics.wav", + output_audio.cpu(), + sample_rate_audio, + ) + + # set console to comfy ComfyUI-0.2.4/custom_nodes and run below command + # export coffy_local_dev=1 + # python3 -m ComfyUI_SignalProcessing.processors.SignalProcessingHarmonicsEnhancer \ No newline at end of file diff --git a/processors/SignalProcessingLoadAudio.py b/processors/SignalProcessingLoadAudio.py index c03e350..2e18bd3 100644 --- a/processors/SignalProcessingLoadAudio.py +++ b/processors/SignalProcessingLoadAudio.py @@ -9,7 +9,7 @@ Description: Audio loading node """ -import sys,os +import sys, os sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy")) @@ -17,24 +17,30 @@ from ..core.io import from_disk_as_dict_3d import folder_paths -class SignalProcessingLoadAudio(): - supported_formats = ['wav','mp3','ogg','m4a','flac','mp4'] - input_dir = os.path.join(folder_paths.get_input_directory(),'samples') + +class SignalProcessingLoadAudio: + supported_formats = ["wav", "mp3", "ogg", "m4a", "flac", "mp4"] + input_dir = os.path.join(folder_paths.get_input_directory(), "samples") + @classmethod def INPUT_TYPES(s): - supported_extensions = tuple(f".{fmt.lower()}" for fmt in SignalProcessingLoadAudio.supported_formats) + supported_extensions = tuple( + f".{fmt.lower()}" for fmt in SignalProcessingLoadAudio.supported_formats + ) files, _ = folder_paths.recursive_search(SignalProcessingLoadAudio.input_dir) - filtered_files = [ - x for x in files - if x.lower().endswith(supported_extensions) + filtered_files = [x for x in files if x.lower().endswith(supported_extensions)] + files = [ + os.path.join(SignalProcessingLoadAudio.input_dir, x) for x in filtered_files ] - files = [os.path.join(SignalProcessingLoadAudio.input_dir,x) for x in filtered_files] return { - "required": { + "required": { "audio_file": (sorted(files), {"image_upload": True}), - "gain": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 8.0, "step": 0.01}), + "gain": ( + "FLOAT", + {"default": 1.0, "min": 0.0, "max": 8.0, "step": 0.01}, + ), }, } @@ -44,4 +50,4 @@ class SignalProcessingLoadAudio(): FUNCTION = "process" def process(self, audio_file, gain): - return from_disk_as_dict_3d(audio_file=audio_file,gain=gain) \ No newline at end of file + return from_disk_as_dict_3d(audio_file=audio_file, gain=gain) diff --git a/processors/SignalProcessingLoudness.py b/processors/SignalProcessingLoudness.py index f50b3a4..7beab68 100644 --- a/processors/SignalProcessingLoudness.py +++ b/processors/SignalProcessingLoudness.py @@ -12,6 +12,7 @@ Description: from ..core.io import audio_from_comfy_2d from ..core.loudness import get_loudness + class SignalProcessingLoudness: @classmethod def INPUT_TYPES(cls): @@ -26,13 +27,9 @@ class SignalProcessingLoudness: CATEGORY = "Audio Processing" FUNCTION = "process" - def process( - self, - audio_input - ): - waveform, sample_rate = audio_from_comfy_2d(audio_input,try_gpu=True) - - loudness : float = get_loudness(waveform,sample_rate) + def process(self, audio_input): + waveform, sample_rate = audio_from_comfy_2d(audio_input, try_gpu=True) + + loudness: float = get_loudness(waveform, sample_rate) return (loudness,) - diff --git a/processors/SignalProcessingMixdown.py b/processors/SignalProcessingMixdown.py index 5a69511..83f6eb5 100644 --- a/processors/SignalProcessingMixdown.py +++ b/processors/SignalProcessingMixdown.py @@ -16,6 +16,8 @@ import torchaudio from ..core.io import audio_to_comfy_3d from ..core.loudness import lufs_normalization + + class SignalProcessingMixdown: @classmethod def INPUT_TYPES(cls) -> Dict: @@ -24,9 +26,12 @@ class SignalProcessingMixdown: "audio_inputs": ("AUDIO_LIST", {"default": []}), }, "optional": { - "gain_factors": ("FLOAT_LIST", {"default": [], "min": 0.0, "max": 2.0, "step": 0.1}), + "gain_factors": ( + "FLOAT_LIST", + {"default": [], "min": 0.0, "max": 2.0, "step": 0.1}, + ), # If empty, default to [1.0] * num_audios - } + }, } RETURN_TYPES = ("AUDIO",) @@ -60,26 +65,33 @@ class SignalProcessingMixdown: if not gain_factors: gain_factors = [1.0] * num_audios elif len(gain_factors) != num_audios: - raise ValueError(f"Number of gain factors ({len(gain_factors)}) does not match number of audio inputs ({num_audios}).") + raise ValueError( + f"Number of gain factors ({len(gain_factors)}) does not match number of audio inputs ({num_audios})." + ) # Extract sample rates and verify consistency - sample_rates = [audio['sample_rate'] for audio in audio_inputs] + sample_rates = [audio["sample_rate"] for audio in audio_inputs] target_sample_rate = sample_rates[0] for idx, sr in enumerate(sample_rates): if sr != target_sample_rate: - resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sample_rate) - resampler.to(device= audio_inputs[idx]['waveform'].device, dtype=audio_inputs[idx]['waveform'].dtype) - audio_inputs[idx]['waveform'] = resampler(audio_inputs[idx]['waveform']) - audio_inputs[idx]['sample_rate'] = target_sample_rate + resampler = torchaudio.transforms.Resample( + orig_freq=sr, new_freq=target_sample_rate + ) + resampler.to( + device=audio_inputs[idx]["waveform"].device, + dtype=audio_inputs[idx]["waveform"].dtype, + ) + audio_inputs[idx]["waveform"] = resampler(audio_inputs[idx]["waveform"]) + audio_inputs[idx]["sample_rate"] = target_sample_rate # Determine the maximum length among all audio inputs - lengths = [audio['waveform'].shape[-1] for audio in audio_inputs] + lengths = [audio["waveform"].shape[-1] for audio in audio_inputs] max_length = max(lengths) # Pad or truncate each audio to match the maximum length and apply gain for idx, audio in enumerate(audio_inputs): - waveform = audio['waveform'] + waveform = audio["waveform"] current_length = waveform.shape[-1] gain = gain_factors[idx] @@ -94,13 +106,13 @@ class SignalProcessingMixdown: # Apply gain waveform = waveform * gain - audio['waveform'] = waveform + audio["waveform"] = waveform # Sum all waveforms to create the mix - mixed_waveform = torch.zeros_like(audio_inputs[0]['waveform']) + mixed_waveform = torch.zeros_like(audio_inputs[0]["waveform"]) for idx, audio in enumerate(audio_inputs): - mixed_waveform += audio['waveform'] + mixed_waveform += audio["waveform"] - mixed_waveform = lufs_normalization(mixed_waveform,target_sample_rate) + mixed_waveform = lufs_normalization(mixed_waveform, target_sample_rate) - return audio_to_comfy_3d(mixed_waveform,target_sample_rate) \ No newline at end of file + return audio_to_comfy_3d(mixed_waveform, target_sample_rate) diff --git a/processors/SignalProcessingNormalizer.py b/processors/SignalProcessingNormalizer.py index 5777077..ed81efb 100644 --- a/processors/SignalProcessingNormalizer.py +++ b/processors/SignalProcessingNormalizer.py @@ -10,7 +10,13 @@ Description: """ from ..core.io import audio_to_comfy_3d, audio_from_comfy_2d -from ..core.loudness import rms_normalization, lufs_normalization, peak_normalization, automatic_gain_control +from ..core.loudness import ( + rms_normalization, + lufs_normalization, + peak_normalization, + automatic_gain_control, +) + class SignalProcessingNormalizer: @classmethod @@ -18,12 +24,27 @@ class SignalProcessingNormalizer: return { "required": { "audio_input": ("AUDIO",), - "mode" : (["lufs","rms", "peak","auto"],), - "target_rms": ("FLOAT", {"default": 0.1, "min": 0, "max": 10.0, "step": 0.1}), - "target_lufs_db": ("FLOAT", {"default": -14.0, "min": -100, "max": 100.0, "step": 0.1}), - "target_peak": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.1}), - "target_auto": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.1}), - "target_auto_alpha": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 10.0, "step": 0.1}) + "mode": (["lufs", "rms", "peak", "auto"],), + "target_rms": ( + "FLOAT", + {"default": 0.1, "min": 0, "max": 10.0, "step": 0.1}, + ), + "target_lufs_db": ( + "FLOAT", + {"default": -14.0, "min": -100, "max": 100.0, "step": 0.1}, + ), + "target_peak": ( + "FLOAT", + {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.1}, + ), + "target_auto": ( + "FLOAT", + {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.1}, + ), + "target_auto_alpha": ( + "FLOAT", + {"default": 0.1, "min": 0.0, "max": 10.0, "step": 0.1}, + ), }, } @@ -35,27 +56,29 @@ class SignalProcessingNormalizer: def process( self, audio_input, - mode : str, - target_rms : float, - target_lufs_db : float, - target_peak : float, - target_auto : float, - target_auto_alpha : float - + mode: str, + target_rms: float, + target_lufs_db: float, + target_peak: float, + target_auto: float, + target_auto_alpha: float, ): - waveform, sample_rate = audio_from_comfy_2d(audio_input,try_gpu=True) + waveform, sample_rate = audio_from_comfy_2d(audio_input, try_gpu=True) - if mode == 'rms': - processed_waveform = rms_normalization(waveform,target_rms) - elif mode == 'lufs': - processed_waveform = lufs_normalization(waveform,sample_rate,target_lufs_db) - elif mode == 'peak': - processed_waveform = peak_normalization(waveform,target_peak) - elif mode == 'auto': - processed_waveform = automatic_gain_control(waveform,target_auto,target_auto_alpha) + if mode == "rms": + processed_waveform = rms_normalization(waveform, target_rms) + elif mode == "lufs": + processed_waveform = lufs_normalization( + waveform, sample_rate, target_lufs_db + ) + elif mode == "peak": + processed_waveform = peak_normalization(waveform, target_peak) + elif mode == "auto": + processed_waveform = automatic_gain_control( + waveform, target_auto, target_auto_alpha + ) else: processed_waveform = waveform - return audio_to_comfy_3d(processed_waveform,sample_rate) - + return audio_to_comfy_3d(processed_waveform, sample_rate) diff --git a/visuals/SignalProcessingSpectrogram.py b/visuals/SignalProcessingSpectrogram.py index dac2e3e..265632d 100644 --- a/visuals/SignalProcessingSpectrogram.py +++ b/visuals/SignalProcessingSpectrogram.py @@ -22,21 +22,31 @@ import matplotlib.pyplot as plt from ..core.io import audio_to_comfy_3d, audio_from_comfy_3d, audio_from_comfy_2d from ..core.loudness import lufs_normalization, get_loudness + class SignalProcessingSpectrogram: @classmethod def INPUT_TYPES(cls): - cmaps = ['viridis', 'plasma', 'inferno', 'magma', 'cividis'] + cmaps = ["viridis", "plasma", "inferno", "magma", "cividis"] return { "required": { "audio_input": ("AUDIO",), "color_map": (cmaps,), }, "optional": { - "n_fft": ("INT", {"default": 4096, "min": 512, "max": 8192, "step": 256}), - "hop_length": ("INT", {"default": 128, "min": 64, "max": 4096, "step": 128}), + "n_fft": ( + "INT", + {"default": 4096, "min": 512, "max": 8192, "step": 256}, + ), + "hop_length": ( + "INT", + {"default": 128, "min": 64, "max": 4096, "step": 128}, + ), "n_mels": ("INT", {"default": 512, "min": 32, "max": 2048, "step": 32}), - "top_db": ("FLOAT", {"default": 80.0, "min": 10.0, "max": 100.0, "step": 5.0}), - } + "top_db": ( + "FLOAT", + {"default": 80.0, "min": 10.0, "max": 100.0, "step": 5.0}, + ), + }, } RETURN_TYPES = ("IMAGE",) @@ -44,11 +54,21 @@ class SignalProcessingSpectrogram: CATEGORY = "Audio Processing" FUNCTION = "process" - def process(self, audio_input, color_map, n_fft=2048, hop_length=512, n_mels=128, top_db=80.0): - waveform = audio_input.get('waveform') # [channels, samples] or [batch, channels, samples] - sample_rate = audio_input.get('sample_rate') + def process( + self, + audio_input, + color_map, + n_fft=2048, + hop_length=512, + n_mels=128, + top_db=80.0, + ): + waveform = audio_input.get( + "waveform" + ) # [channels, samples] or [batch, channels, samples] + sample_rate = audio_input.get("sample_rate") - #waveform, sample_rate = audio_from_comfy_2d(audio_input) + # waveform, sample_rate = audio_from_comfy_2d(audio_input) # Convert to mono by averaging channels if waveform.ndim == 3: @@ -74,9 +94,9 @@ class SignalProcessingSpectrogram: hop_length=hop_length, n_mels=n_mels, power=2.0, - norm='slaney', - mel_scale='htk', - ).to(waveform.device, dtype = waveform.dtype) + norm="slaney", + mel_scale="htk", + ).to(waveform.device, dtype=waveform.dtype) spectrogram = spectrogram_transform(waveform) # [1, n_mels, time_frames] # Convert to decibel scale @@ -84,7 +104,9 @@ class SignalProcessingSpectrogram: spectrogram_db = amplitude_to_db(spectrogram) # [1, n_mels, time_frames] # Convert to numpy - spectrogram_db = spectrogram_db.squeeze().detach().cpu().numpy() # [n_mels, time_frames] + spectrogram_db = ( + spectrogram_db.squeeze().detach().cpu().numpy() + ) # [n_mels, time_frames] # Clip spectrogram to a range for better contrast spectrogram_db = np.clip(spectrogram_db, -top_db, 0.0) @@ -94,10 +116,14 @@ class SignalProcessingSpectrogram: # Apply a colormap (e.g., 'inferno') using matplotlib cmap = plt.get_cmap(color_map) - spectrogram_colored = cmap(spectrogram_normalized) # [n_mels, time_frames, 4] RGBA + spectrogram_colored = cmap( + spectrogram_normalized + ) # [n_mels, time_frames, 4] RGBA # Convert to RGB by removing alpha channel - spectrogram_rgb = (spectrogram_colored[:, :, :3] * 255).astype(np.uint8) # [n_mels, time_frames, 3] + spectrogram_rgb = (spectrogram_colored[:, :, :3] * 255).astype( + np.uint8 + ) # [n_mels, time_frames, 3] spectrogram_rgb = np.squeeze(spectrogram_rgb) # Check the shape and adjust if necessary @@ -112,16 +138,15 @@ class SignalProcessingSpectrogram: # Optionally resize for better resolution spectrogram_image = spectrogram_image.resize( - (spectrogram_image.width * 2, spectrogram_image.height * 2), - Image.BILINEAR + (spectrogram_image.width * 2, spectrogram_image.height * 2), Image.BILINEAR ) # Convert to numpy array and normalize to [0,1] image_np = np.array(spectrogram_image).astype(np.float32) / 255.0 # [H, W, 3] # Convert to torch tensor and add batch dimension - #image_tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0) # [1, 3, H, W] + # image_tensor = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0) # [1, 3, H, W] image = torch.from_numpy(image_np)[None,] - return (image, ) \ No newline at end of file + return (image,) diff --git a/visuals/SignalProcessingWaveform.py b/visuals/SignalProcessingWaveform.py index ef2f444..94248dd 100644 --- a/visuals/SignalProcessingWaveform.py +++ b/visuals/SignalProcessingWaveform.py @@ -16,10 +16,12 @@ import numpy as np import matplotlib.pyplot as plt from ..core.utilities import comfy_root_to_syspath -comfy_root_to_syspath() # add comfy to sys path for dev + +comfy_root_to_syspath() # add comfy to sys path for dev from ..core.io import audio_to_comfy_3d + class SignalProcessingWaveform: @classmethod def INPUT_TYPES(cls): @@ -30,10 +32,16 @@ class SignalProcessingWaveform: "optional": { "color": ("STRING", {"default": "black"}), "background_color": ("STRING", {"default": "white"}), - "width": ("INT", {"default": 800, "min": 100, "max": 4000, "step": 100}), + "width": ( + "INT", + {"default": 800, "min": 100, "max": 4000, "step": 100}, + ), "height": ("INT", {"default": 200, "min": 50, "max": 1000, "step": 50}), - "line_width": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}), - } + "line_width": ( + "FLOAT", + {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}, + ), + }, } RETURN_TYPES = ("IMAGE",) @@ -41,9 +49,19 @@ class SignalProcessingWaveform: CATEGORY = "Audio Processing" FUNCTION = "process" - def process(self, audio_input, color="white", background_color="black", width=800, height=200, line_width=1.0): - waveform = audio_input.get('waveform') # [channels, samples] or [batch, channels, samples] - sample_rate = audio_input.get('sample_rate') + def process( + self, + audio_input, + color="white", + background_color="black", + width=800, + height=200, + line_width=1.0, + ): + waveform = audio_input.get( + "waveform" + ) # [channels, samples] or [batch, channels, samples] + sample_rate = audio_input.get("sample_rate") # Convert to mono by averaging channels if waveform.ndim == 3: @@ -63,13 +81,13 @@ class SignalProcessingWaveform: raise ValueError(f"Unsupported waveform shape: {waveform.shape}") # Convert waveform to numpy - waveform = waveform.to(dtype = torch.float32) + waveform = waveform.to(dtype=torch.float32) waveform_np = waveform.squeeze().detach().cpu().numpy() # [samples] # Create a matplotlib figure without axes - plt.figure(figsize=(width/100, height/100), dpi=96) - plt.axis('off') - plt.margins(0,0) + plt.figure(figsize=(width / 100, height / 100), dpi=96) + plt.axis("off") + plt.margins(0, 0) plt.gca().set_facecolor(background_color) plt.gca().set_position([0, 0, 1, 1]) @@ -80,7 +98,7 @@ class SignalProcessingWaveform: # Save the plot to a buffer buf = BytesIO() - plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0) + plt.savefig(buf, format="png", bbox_inches="tight", pad_inches=0) plt.close() # Load the image from the buffer @@ -96,7 +114,8 @@ class SignalProcessingWaveform: # Convert to torch tensor and add batch dimension image = torch.from_numpy(image_np)[None,] - return (image, ) + return (image,) + class SignalProcessingWaveform2: @classmethod @@ -108,10 +127,16 @@ class SignalProcessingWaveform2: "optional": { "color": ("STRING", {"default": "black"}), "background_color": ("STRING", {"default": "white"}), - "width": ("INT", {"default": 800, "min": 100, "max": 4000, "step": 100}), + "width": ( + "INT", + {"default": 800, "min": 100, "max": 4000, "step": 100}, + ), "height": ("INT", {"default": 200, "min": 50, "max": 1000, "step": 50}), - "line_width": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}), - } + "line_width": ( + "FLOAT", + {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}, + ), + }, } RETURN_TYPES = ("IMAGE",) @@ -119,9 +144,19 @@ class SignalProcessingWaveform2: CATEGORY = "Audio Processing" FUNCTION = "process" - def process(self, audio_input, color="black", background_color="white", width=800, height=200, line_width=1.0): - waveform = audio_input.get('waveform') # [channels, samples] or [batch, channels, samples] - sample_rate = audio_input.get('sample_rate') + def process( + self, + audio_input, + color="black", + background_color="white", + width=800, + height=200, + line_width=1.0, + ): + waveform = audio_input.get( + "waveform" + ) # [channels, samples] or [batch, channels, samples] + sample_rate = audio_input.get("sample_rate") # Convert to mono by averaging channels if waveform.ndim == 3: @@ -146,7 +181,7 @@ class SignalProcessingWaveform2: # Create a matplotlib figure without axes plt.figure(figsize=(width / 100, height / 100), dpi=96) - plt.axis('off') + plt.axis("off") plt.margins(0, 0) ax = plt.gca() ax.set_facecolor(background_color) @@ -159,7 +194,7 @@ class SignalProcessingWaveform2: # Save the plot to a buffer buf = BytesIO() - plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0) + plt.savefig(buf, format="png", bbox_inches="tight", pad_inches=0) plt.close() # Load the image from the buffer @@ -175,15 +210,16 @@ class SignalProcessingWaveform2: # Convert to torch tensor and add batch dimension image = torch.from_numpy(image_np).permute(2, 0, 1).unsqueeze(0) # [1, 3, H, W] - return (image, ) + return (image,) + if __name__ == "__main__": from pathlib import Path from ..core.io import from_disk_as_raw_2d, audio_to_comfy_3d - + node = SignalProcessingWaveform() - samples_path = Path('ComfyUI_SignalProcessing/audio/inputs/song.mp4') + samples_path = Path("ComfyUI_SignalProcessing/audio/inputs/song.mp4") source_path = samples_path.absolute() source_audio, source_audio_sample_rate = from_disk_as_raw_2d(source_path) @@ -192,6 +228,4 @@ if __name__ == "__main__": result = node.process(input)[0] - print('result',result) - - + print("result", result)