commit 08f671357d1b4f9f846d06d091e3053a5e25691f Author: Jarod Mica Date: Sun Dec 17 16:35:11 2023 -0800 first commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..d316141 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +/models +/training +/voices +/bin diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..17672a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,141 @@ +# ignores user files +/venv/ +/models/* +/training/* +/config/* + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +.idea/* +.models/* +.custom/* +results/* +debug_states/* \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..3a99e7f --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "tortoise-tts"] + path = modules/tortoise-tts + url = https://github.com/JarodMica/tortoise-tts.git +[submodule "dlas"] + path = modules/dlas + url = https://github.com/JarodMica/DL-Art-School.git diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7ff4dd3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,37 @@ +FROM nvidia/cuda:11.8.0-cudnn8-devel-ubuntu22.04 + +ARG DEBIAN_FRONTEND=noninteractive +ARG TZ=UTC +ARG MINICONDA_VERSION=23.1.0-1 +ARG PYTHON_VERSION=3.9.13 + +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone +RUN apt-get update +RUN apt install -y curl wget git ffmpeg +RUN adduser --disabled-password --gecos '' --shell /bin/bash user +USER user +ENV HOME=/home/user +WORKDIR $HOME +RUN mkdir $HOME/.cache $HOME/.config && chmod -R 777 $HOME +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-py39_$MINICONDA_VERSION-Linux-x86_64.sh +RUN chmod +x Miniconda3-py39_$MINICONDA_VERSION-Linux-x86_64.sh +RUN ./Miniconda3-py39_$MINICONDA_VERSION-Linux-x86_64.sh -b -p /home/user/miniconda +ENV PATH="$HOME/miniconda/bin:$PATH" +RUN conda init +RUN conda install python=$PYTHON_VERSION +RUN python3 -m pip install --upgrade pip +RUN pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 + +RUN mkdir $HOME/ai-voice-cloning +WORKDIR $HOME/ai-voice-cloning +COPY --chown=user:user modules modules + +RUN python3 -m pip install -r ./modules/tortoise-tts/requirements.txt +RUN python3 -m pip install -e ./modules/tortoise-tts/ +RUN python3 -m pip install -r ./modules/dlas/requirements.txt +RUN python3 -m pip install -e ./modules/dlas/ +ADD requirements.txt requirements.txt +RUN python3 -m pip install -r ./requirements.txt +ADD --chown=user:user . $HOME/ai-voice-cloning + +CMD ["python", "./src/main.py", "--listen", "0.0.0.0:7680"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..20db68e --- /dev/null +++ b/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 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 . \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c69509b --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# AI Voice Cloning + +> **Note** I do not plan on actively working on improvements/enhancements for this project, this is mainly meant to keep the repo in a working state in the case the original git.ecker goes down or necessary package changes need to be made. + +This repo is a fork/reupload of the one originally located here: https://git.ecker.tech/mrq/ai-voice-cloning. All of the work that was put into it to incoporate training with DLAS and inference with Tortoise belong to mrq, the author of the original ai-voice-cloning repo. + +## Setup + +TBD + +## Documentation + +TBD + +## Bug Reporting + +If you run into any problems, please open up a new issue on the issues tab. \ No newline at end of file diff --git a/bin/.gitkeep b/bin/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/changelog.md b/changelog.md new file mode 100644 index 0000000..faedff8 --- /dev/null +++ b/changelog.md @@ -0,0 +1,4 @@ +# Changelogs & Notes + +## 12/17/2023 +- Changed the \ No newline at end of file diff --git a/config/.gitignore b/config/.gitignore new file mode 100644 index 0000000..c96a04f --- /dev/null +++ b/config/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/deepspeed-0.8.3+6eca037c-cp39-cp39-win_amd64.whl b/deepspeed-0.8.3+6eca037c-cp39-cp39-win_amd64.whl new file mode 100644 index 0000000..dd8170e Binary files /dev/null and b/deepspeed-0.8.3+6eca037c-cp39-cp39-win_amd64.whl differ diff --git a/models/.gitignore b/models/.gitignore new file mode 100644 index 0000000..c96a04f --- /dev/null +++ b/models/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/modules/.gitignore b/modules/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/modules/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/notebook_colab.ipynb b/notebook_colab.ipynb new file mode 100644 index 0000000..744ba56 --- /dev/null +++ b/notebook_colab.ipynb @@ -0,0 +1,222 @@ +{ + "nbformat":4, + "nbformat_minor":0, + "metadata":{ + "colab":{ + "private_outputs":true, + "provenance":[ + + ] + }, + "kernelspec":{ + "name":"python3", + "display_name":"Python 3" + }, + "language_info":{ + "name":"python" + }, + "accelerator":"GPU", + "gpuClass":"standard" + }, + "cells":[ + { + "cell_type":"markdown", + "source":[ + "## Initialization" + ], + "metadata":{ + "id":"ni41hmE03DL6" + } + }, + { + "cell_type":"code", + "execution_count":null, + "metadata":{ + "id":"FtsMKKfH18iM" + }, + "outputs":[ + + ], + "source":[ + "!apt install python3.10-venv\n", + "!git clone https://git.ecker.tech/mrq/ai-voice-cloning/\n", + "%cd /content/ai-voice-cloning\n", + "# get local dependencies\n", + "!git submodule init\n", + "!git submodule update --remote\n", + "# setup venv\n", + "!python3 -m venv venv\n", + "!source ./venv/bin/activate\n", + "!python3 -m pip install --upgrade pip # just to be safe\n", + "# CUDA\n", + "!pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118\n", + "# install requirements\n", + "!python3 -m pip install -r ./modules/tortoise-tts/requirements.txt # install TorToiSe requirements\n", + "!python3 -m pip install -e ./modules/tortoise-tts/ # install TorToiSe\n", + "!python3 -m pip install -r ./modules/dlas/requirements.txt # instal DLAS requirements, last, because whisperx will break a dependency here\n", + "!python3 -m pip install -e ./modules/dlas/ # install DLAS\n", + "!python3 -m pip install -r ./requirements.txt # install local requirements" + ] + }, + { + "cell_type":"markdown", + "source":[ + "# Update Repos" + ], + "metadata":{ + "id":"IzrGt5IcHlAD" + } + }, + { + "cell_type":"code", + "source":[ + "# for my debugging purposes\n", + "%cd /content/ai-voice-cloning/\n", + "!./update.sh" + ], + "metadata":{ + "id":"3DktoOXSHmtw" + }, + "execution_count":null, + "outputs":[ + + ] + }, + { + "cell_type":"markdown", + "source":[ + "# Mount Drive" + ], + "metadata":{ + "id":"2Y4t9zDIZMTg" + } + }, + { + "cell_type":"code", + "source":[ + "# only run once, this will save all userdata to your Drive\n", + "# it shouldn't delete through symlinks, but you never know\n", + "\n", + "from google.colab import drive\n", + "\n", + "%cd /content/ai-voice-cloning\n", + "drive.flush_and_unmount()\n", + "!rm -r ./{training,results,voices,config}\n", + "drive.mount('/content/drive')\n", + "!mkdir /content/drive/MyDrive/ai-voice-cloning/\n", + "!mv /content/drive/MyDrive/{training,results,voices,config} /content/drive/MyDrive/ai-voice-cloning\n", + "!mkdir /content/drive/MyDrive/ai-voice-cloning/{training,results,voices,config}\n", + "!ln -s /content/drive/MyDrive/ai-voice-cloning/{training,results,voices,config} ./" + ], + "metadata":{ + "id":"SGt9gyvubveT" + }, + "execution_count":null, + "outputs":[ + + ] + }, + { + "cell_type":"markdown", + "source":[ + "## Running" + ], + "metadata":{ + "id":"EM3iNqgJF6Be" + } + }, + { + "cell_type":"code", + "source":[ + "%cd /content/ai-voice-cloning/\n", + "!source ./venv/bin/activate\n", + "!python3 ./src/main.py --share" + ], + "metadata":{ + "id":"QRA8jF3cF-YJ" + }, + "execution_count":null, + "outputs":[ + + ] + }, + { + "cell_type":"markdown", + "source":[ + "# Restart Runtime" + ], + "metadata":{ + "id":"vH9KU7SMGDxb" + } + }, + { + "cell_type":"code", + "source":[ + "exit()" + ], + "metadata":{ + "id":"EWeyUPvgGDX5" + }, + "execution_count":null, + "outputs":[ + + ] + }, + { + "cell_type":"markdown", + "source":[ + "# Fallback Training" + ], + "metadata":{ + "id":"ggLY9A9KA21D" + } + }, + { + "cell_type":"code", + "source":[ + "# This is in case you can't get training through the web UI\n", + "%cd /content/ai-voice-cloning\n", + "!python ./dlas/codes/train.py -opt ./training/finetune.yaml" + ], + "metadata":{ + "id":"-KayB8klA5tY" + }, + "execution_count":null, + "outputs":[ + + ] + }, + { + "cell_type":"markdown", + "source":[ + "## Exporting" + ], + "metadata":{ + "id":"2AnVQxEJx47p" + } + }, + { + "cell_type":"code", + "source":[ + "# if you're not using drive mounting\n", + "%cd /content/ai-voice-cloning\n", + "!apt install -y p7zip-full\n", + "from datetime import datetime\n", + "timestamp = datetime.now().strftime('%m-%d-%Y_%H:%M:%S')\n", + "!mkdir -p \"../{timestamp}/results\"\n", + "!mv ./results/* \"../{timestamp}/results/.\"\n", + "!mv ./training/* \"../{timestamp}/training/.\"\n", + "!7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -md=32m -ms=on \"../{timestamp}.7z\" \"../{timestamp}/\"\n", + "!ls ~/\n", + "!echo \"Finished zipping, archive is available at {timestamp}.7z\"" + ], + "metadata":{ + "id":"YOACiDCXx72G" + }, + "execution_count":null, + "outputs":[ + + ] + } + ] +} \ No newline at end of file diff --git a/notebook_paperspace.ipynb b/notebook_paperspace.ipynb new file mode 100644 index 0000000..8f8aaf6 --- /dev/null +++ b/notebook_paperspace.ipynb @@ -0,0 +1,132 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "ni41hmE03DL6" + }, + "source": [ + "## Initialization" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "FtsMKKfH18iM" + }, + "source": [ + "!sudo apt update\n", + "!sudo apt-get install python3.9-venv -y\n", + "%cd /notebooks/\n", + "!git clone https://git.ecker.tech/mrq/ai-voice-cloning/\n", + "!ln -s ./ai-voice-cloning/models/ ./\n", + "%cd ai-voice-cloning\n", + "!./setup-cuda.sh\n", + "#!./update.sh" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "IzrGt5IcHlAD" + }, + "source": [ + "# Update Repos" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "3DktoOXSHmtw" + }, + "source": [ + "# for my debugging purposes\n", + "%cd /notebooks/ai-voice-cloning/\n", + "!sudo apt update\n", + "!sudo apt-get install python3.9-venv -y\n", + "!mkdir -p ~/.cache\n", + "!ln -s /notebooks/ai-voice-cloning/models/voicefixer ~/.cache/.\n", + "!./update-force.sh\n", + "#!git pull\n", + "#!git submodule update --remote" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "o1gkfw3B3JSk" + }, + "source": [ + "## Running" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "c_EQZLTA19c7" + }, + "source": [ + "%cd /notebooks/ai-voice-cloning\n", + "\n", + "!export TORTOISE_MODELS_DIR=/notebooks/ai-voice-cloning/models/tortoise/\n", + "!export TRANSFORMERS_CACHE=/notebooks/ai-voice-cloning/models/transformers/\n", + "\n", + "!./start.sh --share" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "2AnVQxEJx47p" + }, + "source": [ + "## Exporting" + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "YOACiDCXx72G" + }, + "source": [ + "%cd /notebooks/ai-voice-cloning\n", + "!apt install -y p7zip-full\n", + "from datetime import datetime\n", + "timestamp = datetime.now().strftime('%m-%d-%Y_%H:%M:%S')\n", + "!mkdir -p \"../{timestamp}/results\"\n", + "!mv ./results/* \"../{timestamp}/results/.\"\n", + "!mv ./training/* \"../{timestamp}/training/.\"\n", + "!7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -md=32m -ms=on \"../{timestamp}.7z\" \"../{timestamp}/\"\n", + "!ls ~/\n", + "!echo \"Finished zipping, archive is available at {timestamp}.7z\"" + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "private_outputs": true, + "provenance": [] + }, + "gpuClass": "standard", + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.13" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..51c2fc9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,18 @@ +--extra-index-url https://download.pytorch.org/whl/cu118 +torch>=2.1.0 +torchvision +torchaudio + +openai-whisper +more-itertools +ffmpeg-python +gradio<=3.23.0 +music-tag +voicefixer +psutil +phonemizer +pydantic==1.10.11 +websockets +beartype==0.15.0 +pykakasi +rotary-embedding-torch==0.4.0 \ No newline at end of file diff --git a/setup-cuda-bnb.bat b/setup-cuda-bnb.bat new file mode 100644 index 0000000..02b4a82 --- /dev/null +++ b/setup-cuda-bnb.bat @@ -0,0 +1,6 @@ + +git clone https://github.com/JarodMica/bitsandbytes-windows.git .\modules\bitsandbytes-windows\ + +xcopy .\modules\bitsandbytes-windows\bin\* .\venv\Lib\site-packages\bitsandbytes\. /Y +xcopy .\modules\bitsandbytes-windows\bin\cuda_setup\* .\venv\Lib\site-packages\bitsandbytes\cuda_setup\. /Y +xcopy .\modules\bitsandbytes-windows\bin\nn\* .\venv\Lib\site-packages\bitsandbytes\nn\. /Y diff --git a/setup-cuda.bat b/setup-cuda.bat new file mode 100644 index 0000000..d25cdf1 --- /dev/null +++ b/setup-cuda.bat @@ -0,0 +1,20 @@ +git submodule init +git submodule update --remote + +python -m venv venv +call .\venv\Scripts\activate.bat +python -m pip install --upgrade pip +python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 +python -m pip install -r .\modules\tortoise-tts\requirements.txt +python -m pip install -e .\modules\tortoise-tts\ +python -m pip install -r .\modules\dlas\requirements.txt +python -m pip install -e .\modules\dlas\ +python -m pip install -r .\requirements.txt + +# setup BnB +.\setup-cuda-bnb.bat + +del *.sh + +pause +deactivate diff --git a/setup-cuda.sh b/setup-cuda.sh new file mode 100644 index 0000000..2c49c87 --- /dev/null +++ b/setup-cuda.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# get local dependencies +git submodule init +git submodule update --remote +# setup venv +python3 -m venv venv +source ./venv/bin/activate +python3 -m pip install --upgrade pip # just to be safe +# CUDA +pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 +# install requirements +python3 -m pip install -r ./modules/tortoise-tts/requirements.txt # install TorToiSe requirements +python3 -m pip install -e ./modules/tortoise-tts/ # install TorToiSe +python3 -m pip install -r ./modules/dlas/requirements.txt # instal DLAS requirements, last, because whisperx will break a dependency here +python3 -m pip install -e ./modules/dlas/ # install DLAS +python3 -m pip install -r ./requirements.txt # install local requirements + +rm *.bat + +deactivate \ No newline at end of file diff --git a/setup-directml.bat b/setup-directml.bat new file mode 100644 index 0000000..87c7e81 --- /dev/null +++ b/setup-directml.bat @@ -0,0 +1,17 @@ +git submodule init +git submodule update --remote + +python -m venv venv +call .\venv\Scripts\activate.bat +python -m pip install --upgrade pip +python -m pip install torch torchvision torchaudio torch-directml +python -m pip install -r .\modules\tortoise-tts\requirements.txt +python -m pip install -e .\modules\tortoise-tts\ +python -m pip install -r .\modules\dlas\requirements.txt +python -m pip install -e .\modules\dlas\ +python -m pip install -r .\requirements.txt + +del *.sh + +pause +deactivate \ No newline at end of file diff --git a/setup-docker.sh b/setup-docker.sh new file mode 100644 index 0000000..c4ca008 --- /dev/null +++ b/setup-docker.sh @@ -0,0 +1,4 @@ +#!/bin/bash +git submodule init +git submodule update --remote +docker build -t ai-voice-cloning . diff --git a/setup-rocm-bnb.sh b/setup-rocm-bnb.sh new file mode 100644 index 0000000..f94072d --- /dev/null +++ b/setup-rocm-bnb.sh @@ -0,0 +1,11 @@ +#!/bin/bash +source ./venv/bin/activate +# swap to ROCm version of BitsAndBytes +pip3 uninstall -y bitsandbytes + +git clone https://git.ecker.tech/mrq/bitsandbytes-rocm modules/bitsandbytes-rocm +cd modules/bitsandbytes-rocm +make hip +CUDA_VERSION=gfx1030 python setup.py install # assumes you're using a 6XXX series card +python3 -m bitsandbytes # to validate it works +cd ../.. \ No newline at end of file diff --git a/setup-rocm.sh b/setup-rocm.sh new file mode 100644 index 0000000..04a6a96 --- /dev/null +++ b/setup-rocm.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# get local dependencies +git submodule init +git submodule update --remote +# setup venv +python3 -m venv venv +source ./venv/bin/activate +python3 -m pip install --upgrade pip # just to be safe +# ROCM +pip3 install torch==1.13.1 torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm5.2 # 5.4.2 doesn't work for me desu +# install requirements +python3 -m pip install -r ./modules/tortoise-tts/requirements.txt # install TorToiSe requirements +python3 -m pip install -e ./modules/tortoise-tts/ # install TorToiSe +python3 -m pip install -r ./modules/dlas/requirements.txt # instal DLAS requirements +python3 -m pip install -e ./modules/dlas/ # install DLAS +python3 -m pip install -r ./requirements.txt # install local requirements + +rm *.bat + +./setup-rocm-bnb.sh + +deactivate \ No newline at end of file diff --git a/src/api/websocket_server.py b/src/api/websocket_server.py new file mode 100644 index 0000000..85e21cd --- /dev/null +++ b/src/api/websocket_server.py @@ -0,0 +1,84 @@ +import asyncio +import json +from threading import Thread + +from websockets.server import serve + +from utils import generate, get_autoregressive_models, get_voice_list, args, update_autoregressive_model, update_diffusion_model, update_tokenizer + +# this is a not so nice workaround to set values to None if their string value is "None" +def replaceNoneStringWithNone(message): + ignore_fields = ['text'] # list of fields which CAN have "None" as literal String value + + for member in message: + if message[member] == 'None' and member not in ignore_fields: + message[member] = None + + return message + + +async def _handle_generate(websocket, message): + # update args parameters which control the model settings + if message.get('autoregressive_model'): + update_autoregressive_model(message['autoregressive_model']) + + if message.get('diffusion_model'): + update_diffusion_model(message['diffusion_model']) + + if message.get('tokenizer_json'): + update_tokenizer(message['tokenizer_json']) + + if message.get('sample_batch_size'): + global args + args.sample_batch_size = message['sample_batch_size'] + + message['result'] = generate(**message) + await websocket.send(json.dumps(replaceNoneStringWithNone(message))) + + +async def _handle_get_autoregressive_models(websocket, message): + message['result'] = get_autoregressive_models() + await websocket.send(json.dumps(replaceNoneStringWithNone(message))) + + +async def _handle_get_voice_list(websocket, message): + message['result'] = get_voice_list() + await websocket.send(json.dumps(replaceNoneStringWithNone(message))) + + +async def _handle_message(websocket, message): + message = replaceNoneStringWithNone(message) + + if message.get('action') and message['action'] == 'generate': + await _handle_generate(websocket, message) + elif message.get('action') and message['action'] == 'get_voices': + await _handle_get_voice_list(websocket, message) + elif message.get('action') and message['action'] == 'get_autoregressive_models': + await _handle_get_autoregressive_models(websocket, message) + else: + print("websocket: undhandled message: " + message) + + +async def _handle_connection(websocket, path): + print("websocket: client connected") + + async for message in websocket: + try: + await _handle_message(websocket, json.loads(message)) + except ValueError: + print("websocket: malformed json received") + + +async def _run(host: str, port: int): + print(f"websocket: server started on ws://{host}:{port}") + + async with serve(_handle_connection, host, port, ping_interval=None): + await asyncio.Future() # run forever + + +def _run_server(listen_address: str, port: int): + asyncio.run(_run(host=listen_address, port=port)) + + +def start_websocket_server(listen_address: str, port: int): + Thread(target=_run_server, args=[listen_address, port], daemon=True).start() diff --git a/src/cli.py b/src/cli.py new file mode 100644 index 0000000..a8002bd --- /dev/null +++ b/src/cli.py @@ -0,0 +1,66 @@ +import os +import argparse + +if 'TORTOISE_MODELS_DIR' not in os.environ: + os.environ['TORTOISE_MODELS_DIR'] = os.path.realpath(os.path.join(os.getcwd(), './models/tortoise/')) + +if 'TRANSFORMERS_CACHE' not in os.environ: + os.environ['TRANSFORMERS_CACHE'] = os.path.realpath(os.path.join(os.getcwd(), './models/transformers/')) + +os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python' + +from utils import * + +if __name__ == "__main__": + args = setup_args(cli=True) + + default_arguments = import_generate_settings() + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument("--text", default=default_arguments['text']) + parser.add_argument("--delimiter", default=default_arguments['delimiter']) + parser.add_argument("--emotion", default=default_arguments['emotion']) + parser.add_argument("--prompt", default=default_arguments['prompt']) + parser.add_argument("--voice", default=default_arguments['voice']) + parser.add_argument("--mic_audio", default=default_arguments['mic_audio']) + parser.add_argument("--voice_latents_chunks", default=default_arguments['voice_latents_chunks']) + parser.add_argument("--candidates", default=default_arguments['candidates']) + parser.add_argument("--seed", default=default_arguments['seed']) + parser.add_argument("--num_autoregressive_samples", default=default_arguments['num_autoregressive_samples']) + parser.add_argument("--diffusion_iterations", default=default_arguments['diffusion_iterations']) + parser.add_argument("--temperature", default=default_arguments['temperature']) + parser.add_argument("--diffusion_sampler", default=default_arguments['diffusion_sampler']) + parser.add_argument("--breathing_room", default=default_arguments['breathing_room']) + parser.add_argument("--cvvp_weight", default=default_arguments['cvvp_weight']) + parser.add_argument("--top_p", default=default_arguments['top_p']) + parser.add_argument("--diffusion_temperature", default=default_arguments['diffusion_temperature']) + parser.add_argument("--length_penalty", default=default_arguments['length_penalty']) + parser.add_argument("--repetition_penalty", default=default_arguments['repetition_penalty']) + parser.add_argument("--cond_free_k", default=default_arguments['cond_free_k']) + + args, unknown = parser.parse_known_args() + kwargs = { + 'text': args.text, + 'delimiter': args.delimiter, + 'emotion': args.emotion, + 'prompt': args.prompt, + 'voice': args.voice, + 'mic_audio': args.mic_audio, + 'voice_latents_chunks': args.voice_latents_chunks, + 'candidates': args.candidates, + 'seed': args.seed, + 'num_autoregressive_samples': args.num_autoregressive_samples, + 'diffusion_iterations': args.diffusion_iterations, + 'temperature': args.temperature, + 'diffusion_sampler': args.diffusion_sampler, + 'breathing_room': args.breathing_room, + 'cvvp_weight': args.cvvp_weight, + 'top_p': args.top_p, + 'diffusion_temperature': args.diffusion_temperature, + 'length_penalty': args.length_penalty, + 'repetition_penalty': args.repetition_penalty, + 'cond_free_k': args.cond_free_k, + 'experimentals': default_arguments['experimentals'], + } + + tts = load_tts() + generate(**kwargs) \ No newline at end of file diff --git a/src/list_devices.py b/src/list_devices.py new file mode 100644 index 0000000..3726af9 --- /dev/null +++ b/src/list_devices.py @@ -0,0 +1,5 @@ +import torch + +devices = [f"cuda:{i} => {torch.cuda.get_device_name(i)}" for i in range(torch.cuda.device_count())] + +print(devices) \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..0fe5e13 --- /dev/null +++ b/src/main.py @@ -0,0 +1,47 @@ +import os + +if 'TORTOISE_MODELS_DIR' not in os.environ: + os.environ['TORTOISE_MODELS_DIR'] = os.path.realpath(os.path.join(os.getcwd(), './models/tortoise/')) + +if 'TRANSFORMERS_CACHE' not in os.environ: + os.environ['TRANSFORMERS_CACHE'] = os.path.realpath(os.path.join(os.getcwd(), './models/transformers/')) + +os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python' + +from utils import * +from webui import * + +from api.websocket_server import start_websocket_server + + +if __name__ == "__main__": + args = setup_args() + + if args.listen_path is not None and args.listen_path != "/": + import uvicorn + uvicorn.run("main:app", host=args.listen_host, port=args.listen_port if not None else 8000) + else: + webui = setup_gradio() + webui.launch(share=args.share, prevent_thread_lock=True, show_error=True, server_name=args.listen_host, server_port=args.listen_port) + if not args.defer_tts_load: + tts = load_tts() + + if args.websocket_enabled: + start_websocket_server(args.websocket_listen_address, args.websocket_listen_port) + + webui.block_thread() +elif __name__ == "main": + from fastapi import FastAPI + import gradio as gr + + import sys + sys.argv = [sys.argv[0]] + + app = FastAPI() + args = setup_args() + webui = setup_gradio() + app = gr.mount_gradio_app(app, webui, path=args.listen_path) + + if not args.defer_tts_load: + tts = load_tts() + diff --git a/src/train.py b/src/train.py new file mode 100644 index 0000000..89edae6 --- /dev/null +++ b/src/train.py @@ -0,0 +1,64 @@ +import os +import sys +import argparse +import yaml +import datetime + +from torch.distributed.run import main as torchrun + +# this is effectively just copy pasted and cleaned up from the __main__ section of training.py +def train(config_path, launcher='none'): + opt = option.parse(config_path, is_train=True) + + if launcher == 'none' and opt['gpus'] > 1: + return torchrun([f"--nproc_per_node={opt['gpus']}", "./src/train.py", "--yaml", config_path, "--launcher=pytorch"]) + + trainer = tr.Trainer() + if launcher == 'none': + opt['dist'] = False + trainer.rank = -1 + if len(opt['gpu_ids']) == 1: + torch.cuda.set_device(opt['gpu_ids'][0]) + print('Disabled distributed training.') + else: + opt['dist'] = True + tr.init_dist('nccl', timeout=datetime.timedelta(seconds=5*60)) + trainer.world_size = torch.distributed.get_world_size() + trainer.rank = torch.distributed.get_rank() + torch.cuda.set_device(torch.distributed.get_rank()) + + trainer.init(config_path, opt, launcher, '') + trainer.do_training() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--yaml', type=str, help='Path to training configuration file.', default='./training/voice/train.yml', nargs='+') # ugh + parser.add_argument('--launcher', choices=['none', 'pytorch'], default='none', help='Job launcher') + args = parser.parse_args() + args.yaml = " ".join(args.yaml) # absolutely disgusting + config_path = args.yaml + + with open(config_path, 'r') as file: + opt_config = yaml.safe_load(file) + + # yucky override + if "bitsandbytes" in opt_config and not opt_config["bitsandbytes"]: + os.environ['BITSANDBYTES_OVERRIDE_LINEAR'] = '0' + os.environ['BITSANDBYTES_OVERRIDE_EMBEDDING'] = '0' + os.environ['BITSANDBYTES_OVERRIDE_ADAM'] = '0' + os.environ['BITSANDBYTES_OVERRIDE_ADAMW'] = '0' + + try: + import torch_intermediary + if torch_intermediary.OVERRIDE_ADAM: + print("Using BitsAndBytes optimizations") + else: + print("NOT using BitsAndBytes optimizations") + except Exception as e: + pass + + import torch + from dlas import train as tr + from dlas.utils import util, options as option + + train(config_path, args.launcher) \ No newline at end of file diff --git a/src/utils.py b/src/utils.py new file mode 100644 index 0000000..a0f0588 --- /dev/null +++ b/src/utils.py @@ -0,0 +1,4015 @@ +import os +if 'XDG_CACHE_HOME' not in os.environ: + os.environ['XDG_CACHE_HOME'] = os.path.realpath(os.path.join(os.getcwd(), './models/')) + +if 'TORTOISE_MODELS_DIR' not in os.environ: + os.environ['TORTOISE_MODELS_DIR'] = os.path.realpath(os.path.join(os.getcwd(), './models/tortoise/')) + +if 'TRANSFORMERS_CACHE' not in os.environ: + os.environ['TRANSFORMERS_CACHE'] = os.path.realpath(os.path.join(os.getcwd(), './models/transformers/')) + +import argparse +import time +import math +import json +import base64 +import re +import urllib.request +import signal +import gc +import subprocess +import psutil +import yaml +import hashlib +import string +import random + +from tqdm import tqdm +import torch +import torchaudio +import music_tag +import gradio as gr +import gradio.utils +import pandas as pd +import numpy as np + +from glob import glob +from datetime import datetime +from datetime import timedelta + +from tortoise.api import TextToSpeech as TorToise_TTS, MODELS, get_model_path, pad_or_truncate +from tortoise.api_fast import TextToSpeech as Toroise_TTS_Hifi +from tortoise.utils.audio import load_audio, load_voice, load_voices, get_voice_dir, get_voices +from tortoise.utils.text import split_and_recombine_text +from tortoise.utils.device import get_device_name, set_device_name, get_device_count, get_device_vram, get_device_batch_size, do_gc + + +MODELS['dvae.pth'] = "https://huggingface.co/jbetker/tortoise-tts-v2/resolve/3704aea61678e7e468a06d8eea121dba368a798e/.models/dvae.pth" + +WHISPER_MODELS = ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2"] +WHISPER_SPECIALIZED_MODELS = ["tiny.en", "base.en", "small.en", "medium.en"] +WHISPER_BACKENDS = ["openai/whisper", "lightmare/whispercpp", "m-bain/whisperx"] +VOCODERS = ['univnet', 'bigvgan_base_24khz_100band', 'bigvgan_24khz_100band'] +TTSES = ['tortoise'] + +INFERENCING = False +GENERATE_SETTINGS_ARGS = None + +LEARNING_RATE_SCHEMES = {"Multistep": "MultiStepLR", "Cos. Annealing": "CosineAnnealingLR_Restart"} +LEARNING_RATE_SCHEDULE = [ 2, 4, 9, 18, 25, 33, 50 ] + +RESAMPLERS = {} + +MIN_TRAINING_DURATION = 0.6 +MAX_TRAINING_DURATION = 11.6097505669 +MAX_TRAINING_CHAR_LENGTH = 200 + +VALLE_ENABLED = False +BARK_ENABLED = False + +VERBOSE_DEBUG = True + +KKS = None +PYKAKASI_ENABLED = False + +import traceback + +try: + import pykakasi + KKS = pykakasi.kakasi() + PYKAKASI_ENABLED = True +except Exception as e: + #if VERBOSE_DEBUG: + # print(traceback.format_exc()) + pass + +try: + from whisper.normalizers.english import EnglishTextNormalizer + from whisper.normalizers.basic import BasicTextNormalizer + from whisper.tokenizer import LANGUAGES + + print("Whisper detected") +except Exception as e: + if VERBOSE_DEBUG: + print(traceback.format_exc()) + pass + +try: + from vall_e.emb.qnt import encode as valle_quantize + from vall_e.emb.g2p import encode as valle_phonemize + + from vall_e.inference import TTS as VALLE_TTS + + import soundfile + + print("VALL-E detected") + VALLE_ENABLED = True +except Exception as e: + if VERBOSE_DEBUG: + print(traceback.format_exc()) + pass + +if VALLE_ENABLED: + TTSES.append('vall-e') + +# torchaudio.set_audio_backend('soundfile') + +try: + import bark + from bark import text_to_semantic + from bark.generation import SAMPLE_RATE as BARK_SAMPLE_RATE, ALLOWED_PROMPTS, preload_models, codec_decode, generate_coarse, generate_fine, generate_text_semantic, load_codec_model + from bark.api import generate_audio as bark_generate_audio + from encodec.utils import convert_audio + + from scipy.io.wavfile import write as write_wav + + print("Bark detected") + BARK_ENABLED = True +except Exception as e: + if VERBOSE_DEBUG: + print(traceback.format_exc()) + pass + +if BARK_ENABLED: + TTSES.append('bark') + + def semantic_to_audio_tokens( + semantic_tokens, + history_prompt = None, + temp = 0.7, + silent = False, + output_full = False, + ): + coarse_tokens = generate_coarse( + semantic_tokens, history_prompt=history_prompt, temp=temp, silent=silent, use_kv_caching=True + ) + fine_tokens = generate_fine(coarse_tokens, history_prompt=history_prompt, temp=0.5) + + if output_full: + full_generation = { + "semantic_prompt": semantic_tokens, + "coarse_prompt": coarse_tokens, + "fine_prompt": fine_tokens, + } + return full_generation + return fine_tokens + + class Bark_TTS(): + def __init__(self, small=False): + self.input_sample_rate = BARK_SAMPLE_RATE + self.output_sample_rate = BARK_SAMPLE_RATE # args.output_sample_rate + + preload_models( + text_use_gpu=True, + coarse_use_gpu=True, + fine_use_gpu=True, + codec_use_gpu=True, + + text_use_small=small, + coarse_use_small=small, + fine_use_small=small, + + force_reload=False + ) + + self.device = get_device_name() + + try: + from vocos import Vocos + self.vocos_enabled = True + print("Vocos detected") + except Exception as e: + if VERBOSE_DEBUG: + print(traceback.format_exc()) + self.vocos_enabled = False + + try: + from hubert.hubert_manager import HuBERTManager + + hubert_manager = HuBERTManager() + hubert_manager.make_sure_hubert_installed() + hubert_manager.make_sure_tokenizer_installed() + + self.hubert_enabled = True + print("HuBERT detected") + except Exception as e: + if VERBOSE_DEBUG: + print(traceback.format_exc()) + self.hubert_enabled = False + + if self.vocos_enabled: + self.vocos = Vocos.from_pretrained("charactr/vocos-encodec-24khz").to(self.device) + + def create_voice( self, voice ): + transcription_json = f'./training/{voice}/whisper.json' + if not os.path.exists(transcription_json): + raise f"Transcription for voice not found: {voice}" + + transcriptions = json.load(open(transcription_json, 'r', encoding="utf-8")) + candidates = [] + for file in transcriptions: + result = transcriptions[file] + added = 0 + + for segment in result['segments']: + path = file.replace(".wav", f"_{pad(segment['id'], 4)}.wav") + # check if the slice actually exists + if not os.path.exists(f'./training/{voice}/audio/{path}'): + continue + + entry = ( + path, + segment['end'] - segment['start'], + segment['text'] + ) + candidates.append(entry) + added = added + 1 + + # if nothing got added (assuming because nothign was sliced), use the master file + if added == 0: # added < len(result['segments']): + start = 0 + end = 0 + for segment in result['segments']: + start = max( start, segment['start'] ) + end = max( end, segment['end'] ) + + entry = ( + file, + end - start, + result['text'] + ) + candidates.append(entry) + + candidates.sort(key=lambda x: x[1]) + candidate = random.choice(candidates) + audio_filepath = f'./training/{voice}/audio/{candidate[0]}' + text = candidate[-1] + + print("Using as reference:", audio_filepath, text) + + # Load and pre-process the audio waveform + model = load_codec_model(use_gpu=True) + wav, sr = torchaudio.load(audio_filepath) + wav = convert_audio(wav, sr, model.sample_rate, model.channels) + + # generate semantic tokens + + if self.hubert_enabled: + from hubert.pre_kmeans_hubert import CustomHubert + from hubert.customtokenizer import CustomTokenizer + + wav = wav.to(self.device) + + # Extract discrete codes from EnCodec + with torch.no_grad(): + encoded_frames = model.encode(wav.unsqueeze(0)) + codes = torch.cat([encoded[0] for encoded in encoded_frames], dim=-1).squeeze() # [n_q, T] + + # get seconds of audio + seconds = wav.shape[-1] / model.sample_rate + + # Load the HuBERT model + hubert_model = CustomHubert(checkpoint_path='./data/models/hubert/hubert.pt').to(self.device) + + # Load the CustomTokenizer model + tokenizer = CustomTokenizer.load_from_checkpoint('./data/models/hubert/tokenizer.pth').to(self.device) + + semantic_vectors = hubert_model.forward(wav, input_sample_hz=model.sample_rate) + semantic_tokens = tokenizer.get_token(semantic_vectors) + + # move codes to cpu + codes = codes.cpu().numpy() + # move semantic tokens to cpu + semantic_tokens = semantic_tokens.cpu().numpy() + else: + wav = wav.unsqueeze(0).to(self.device) + + # Extract discrete codes from EnCodec + with torch.no_grad(): + encoded_frames = model.encode(wav) + codes = torch.cat([encoded[0] for encoded in encoded_frames], dim=-1).squeeze().cpu().numpy() # [n_q, T] + + # get seconds of audio + seconds = wav.shape[-1] / model.sample_rate + + # generate semantic tokens + semantic_tokens = generate_text_semantic(text, max_gen_duration_s=seconds, top_k=50, top_p=.95, temp=0.7) + + # print(bark.__file__) + bark_location = os.path.dirname(os.path.relpath(bark.__file__)) # './modules/bark/bark/' + output_path = f'./{bark_location}/assets/prompts/' + voice.replace("/", "_") + '.npz' + np.savez(output_path, fine_prompt=codes, coarse_prompt=codes[:2, :], semantic_prompt=semantic_tokens) + + def inference( self, text, voice, text_temp=0.7, waveform_temp=0.7 ): + if voice == "random": + voice = None + else: + if not os.path.exists('./modules/bark/bark/assets/prompts/' + voice + '.npz'): + self.create_voice( voice ) + voice = voice.replace("/", "_") + if voice not in ALLOWED_PROMPTS: + ALLOWED_PROMPTS.add( voice ) + + semantic_tokens = text_to_semantic(text, history_prompt=voice, temp=text_temp, silent=False) + audio_tokens = semantic_to_audio_tokens( semantic_tokens, history_prompt=voice, temp=waveform_temp, silent=False, output_full=False ) + + if self.vocos_enabled: + audio_tokens_torch = torch.from_numpy(audio_tokens).to(self.device) + features = self.vocos.codes_to_features(audio_tokens_torch) + wav = self.vocos.decode(features, bandwidth_id=torch.tensor([2], device=self.device)) + else: + wav = codec_decode( audio_tokens ) + + return ( wav, BARK_SAMPLE_RATE ) + # return (bark_generate_audio(text, history_prompt=voice, text_temp=text_temp, waveform_temp=waveform_temp), BARK_SAMPLE_RATE) + +args = None +tts = None +tts_loading = False +webui = None +voicefixer = None + +whisper_model = None +whisper_align_model = None + +training_state = None + +current_voice = None + +def cleanup_voice_name( name ): + return name.split("/")[-1] + +def resample( waveform, input_rate, output_rate=44100 ): + # mono-ize + waveform = torch.mean(waveform, dim=0, keepdim=True) + + if input_rate == output_rate: + return waveform, output_rate + + key = f'{input_rate}:{output_rate}' + if not key in RESAMPLERS: + RESAMPLERS[key] = torchaudio.transforms.Resample( + input_rate, + output_rate, + lowpass_filter_width=16, + rolloff=0.85, + resampling_method="kaiser_window", + beta=8.555504641634386, + ) + + return RESAMPLERS[key]( waveform ), output_rate + +def generate(**kwargs): + if args.tts_backend == "tortoise": + return generate_tortoise(**kwargs) + if args.tts_backend == "vall-e": + return generate_valle(**kwargs) + if args.tts_backend == "bark": + return generate_bark(**kwargs) + +def generate_bark(**kwargs): + parameters = {} + parameters.update(kwargs) + + voice = parameters['voice'] + progress = parameters['progress'] if 'progress' in parameters else None + if parameters['seed'] == 0: + parameters['seed'] = None + + usedSeed = parameters['seed'] + + global args + global tts + + unload_whisper() + unload_voicefixer() + + if not tts: + # should check if it's loading or unloaded, and load it if it's unloaded + if tts_loading: + raise Exception("TTS is still initializing...") + if progress is not None: + notify_progress("Initializing TTS...", progress=progress) + load_tts() + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + do_gc() + + voice_samples = None + conditioning_latents = None + sample_voice = None + + voice_cache = {} + + def get_settings( override=None ): + settings = { + 'voice': parameters['voice'], + 'text_temp': float(parameters['temperature']), + 'waveform_temp': float(parameters['temperature']), + } + + # could be better to just do a ternary on everything above, but i am not a professional + selected_voice = voice + if override is not None: + if 'voice' in override: + selected_voice = override['voice'] + + for k in override: + if k not in settings: + continue + settings[k] = override[k] + + return settings + + if not parameters['delimiter']: + parameters['delimiter'] = "\n" + elif parameters['delimiter'] == "\\n": + parameters['delimiter'] = "\n" + + if parameters['delimiter'] and parameters['delimiter'] != "" and parameters['delimiter'] in parameters['text']: + texts = parameters['text'].split(parameters['delimiter']) + else: + texts = split_and_recombine_text(parameters['text']) + + full_start_time = time.time() + + outdir = f"{args.results_folder}/{voice}/" + os.makedirs(outdir, exist_ok=True) + + audio_cache = {} + + volume_adjust = torchaudio.transforms.Vol(gain=args.output_volume, gain_type="amplitude") if args.output_volume != 1 else None + + idx = 0 + idx_cache = {} + for i, file in enumerate(os.listdir(outdir)): + filename = os.path.basename(file) + extension = os.path.splitext(filename)[-1][1:] + if extension != "json" and extension != "wav": + continue + match = re.findall(rf"^{cleanup_voice_name(voice)}_(\d+)(?:.+?)?{extension}$", filename) + if match and len(match) > 0: + key = int(match[0]) + idx_cache[key] = True + + if len(idx_cache) > 0: + keys = sorted(list(idx_cache.keys())) + idx = keys[-1] + 1 + + idx = pad(idx, 4) + + def get_name(line=0, candidate=0, combined=False): + name = f"{idx}" + if combined: + name = f"{name}_combined" + elif len(texts) > 1: + name = f"{name}_{line}" + if parameters['candidates'] > 1: + name = f"{name}_{candidate}" + return name + + def get_info( voice, settings = None, latents = True ): + info = {} + info.update(parameters) + + info['time'] = time.time()-full_start_time + info['datetime'] = datetime.now().isoformat() + + info['progress'] = None + del info['progress'] + + if info['delimiter'] == "\n": + info['delimiter'] = "\\n" + + if settings is not None: + for k in settings: + if k in info: + info[k] = settings[k] + return info + + INFERENCING = True + for line, cut_text in enumerate(texts): + tqdm_prefix = f'[{str(line+1)}/{str(len(texts))}]' + print(f"{tqdm_prefix} Generating line: {cut_text}") + start_time = time.time() + + # do setting editing + match = re.findall(r'^(\{.+\}) (.+?)$', cut_text) + override = None + if match and len(match) > 0: + match = match[0] + try: + override = json.loads(match[0]) + cut_text = match[1].strip() + except Exception as e: + raise Exception("Prompt settings editing requested, but received invalid JSON") + + settings = get_settings( override=override ) + + gen = tts.inference(cut_text, **settings ) + + run_time = time.time()-start_time + print(f"Generating line took {run_time} seconds") + + if not isinstance(gen, list): + gen = [gen] + + for j, g in enumerate(gen): + wav, sr = g + name = get_name(line=line, candidate=j) + + settings['text'] = cut_text + settings['time'] = run_time + settings['datetime'] = datetime.now().isoformat() + + # save here in case some error happens mid-batch + if tts.vocos_enabled: + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', wav.cpu(), sr) + else: + write_wav(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', sr, wav) + wav, sr = torchaudio.load(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + + audio_cache[name] = { + 'audio': wav, + 'settings': get_info(voice=override['voice'] if override and 'voice' in override else voice, settings=settings) + } + + del gen + do_gc() + INFERENCING = False + + for k in audio_cache: + audio = audio_cache[k]['audio'] + + audio, _ = resample(audio, tts.output_sample_rate, args.output_sample_rate) + if volume_adjust is not None: + audio = volume_adjust(audio) + + audio_cache[k]['audio'] = audio + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{k}.wav', audio, args.output_sample_rate) + + output_voices = [] + for candidate in range(parameters['candidates']): + if len(texts) > 1: + audio_clips = [] + for line in range(len(texts)): + name = get_name(line=line, candidate=candidate) + audio = audio_cache[name]['audio'] + audio_clips.append(audio) + + name = get_name(candidate=candidate, combined=True) + audio = torch.cat(audio_clips, dim=-1) + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', audio, args.output_sample_rate) + + audio = audio.squeeze(0).cpu() + audio_cache[name] = { + 'audio': audio, + 'settings': get_info(voice=voice), + 'output': True + } + else: + try: + name = get_name(candidate=candidate) + audio_cache[name]['output'] = True + except Exception as e: + for name in audio_cache: + audio_cache[name]['output'] = True + + + if args.voice_fixer: + if not voicefixer: + notify_progress("Loading voicefix...", progress=progress) + load_voicefixer() + + try: + fixed_cache = {} + for name in tqdm(audio_cache, desc="Running voicefix..."): + del audio_cache[name]['audio'] + if 'output' not in audio_cache[name] or not audio_cache[name]['output']: + continue + + path = f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav' + fixed = f'{outdir}/{cleanup_voice_name(voice)}_{name}_fixed.wav' + voicefixer.restore( + input=path, + output=fixed, + cuda=get_device_name() == "cuda" and args.voice_fixer_use_cuda, + #mode=mode, + ) + + fixed_cache[f'{name}_fixed'] = { + 'settings': audio_cache[name]['settings'], + 'output': True + } + audio_cache[name]['output'] = False + + for name in fixed_cache: + audio_cache[name] = fixed_cache[name] + except Exception as e: + print(e) + print("\nFailed to run Voicefixer") + + for name in audio_cache: + if 'output' not in audio_cache[name] or not audio_cache[name]['output']: + if args.prune_nonfinal_outputs: + audio_cache[name]['pruned'] = True + os.remove(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + continue + + output_voices.append(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + + if not args.embed_output_metadata: + with open(f'{outdir}/{cleanup_voice_name(voice)}_{name}.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(audio_cache[name]['settings'], indent='\t') ) + + if args.embed_output_metadata: + for name in tqdm(audio_cache, desc="Embedding metadata..."): + if 'pruned' in audio_cache[name] and audio_cache[name]['pruned']: + continue + + metadata = music_tag.load_file(f"{outdir}/{cleanup_voice_name(voice)}_{name}.wav") + metadata['lyrics'] = json.dumps(audio_cache[name]['settings']) + metadata.save() + + if sample_voice is not None: + sample_voice = (tts.input_sample_rate, sample_voice.numpy()) + + info = get_info(voice=voice, latents=False) + print(f"Generation took {info['time']} seconds, saved to '{output_voices[0]}'\n") + + info['seed'] = usedSeed + if 'latents' in info: + del info['latents'] + + os.makedirs('./config/', exist_ok=True) + with open(f'./config/generate.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(info, indent='\t') ) + + stats = [ + [ parameters['seed'], "{:.3f}".format(info['time']) ] + ] + + return ( + sample_voice, + output_voices, + stats, + ) + +def generate_valle(**kwargs): + parameters = {} + parameters.update(kwargs) + + voice = parameters['voice'] + progress = parameters['progress'] if 'progress' in parameters else None + if parameters['seed'] == 0: + parameters['seed'] = None + + usedSeed = parameters['seed'] + + global args + global tts + + unload_whisper() + unload_voicefixer() + + if not tts: + # should check if it's loading or unloaded, and load it if it's unloaded + if tts_loading: + raise Exception("TTS is still initializing...") + if progress is not None: + notify_progress("Initializing TTS...", progress=progress) + load_tts() + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + do_gc() + + voice_samples = None + conditioning_latents = None + sample_voice = None + + voice_cache = {} + def fetch_voice( voice ): + if voice in voice_cache: + return voice_cache[voice] + + """ + voice_dir = f'./training/{voice}/audio/' + + if not os.path.isdir(voice_dir) or len(os.listdir(voice_dir)) == 0: + voice_dir = f'./voices/{voice}/' + + files = [ f'{voice_dir}/{d}' for d in os.listdir(voice_dir) if d[-4:] == ".wav" ] + """ + + if os.path.isdir(f'./training/{voice}/audio/'): + files = get_voice(name="audio", dir=f"./training/{voice}/", load_latents=False) + else: + files = get_voice(name=voice, load_latents=False) + + # return files + voice_cache[voice] = random.sample(files, k=min(3, len(files))) + return voice_cache[voice] + + def get_settings( override=None ): + settings = { + 'ar_temp': float(parameters['temperature']), + 'nar_temp': float(parameters['temperature']), + 'max_ar_steps': parameters['num_autoregressive_samples'], + } + + # could be better to just do a ternary on everything above, but i am not a professional + selected_voice = voice + if override is not None: + if 'voice' in override: + selected_voice = override['voice'] + + for k in override: + if k not in settings: + continue + settings[k] = override[k] + + settings['references'] = fetch_voice(voice=selected_voice) # [ fetch_voice(voice=selected_voice) for _ in range(3) ] + return settings + + if not parameters['delimiter']: + parameters['delimiter'] = "\n" + elif parameters['delimiter'] == "\\n": + parameters['delimiter'] = "\n" + + if parameters['delimiter'] and parameters['delimiter'] != "" and parameters['delimiter'] in parameters['text']: + texts = parameters['text'].split(parameters['delimiter']) + else: + texts = split_and_recombine_text(parameters['text']) + + full_start_time = time.time() + + outdir = f"{args.results_folder}/{voice}/" + os.makedirs(outdir, exist_ok=True) + + audio_cache = {} + + volume_adjust = torchaudio.transforms.Vol(gain=args.output_volume, gain_type="amplitude") if args.output_volume != 1 else None + + idx = 0 + idx_cache = {} + for i, file in enumerate(os.listdir(outdir)): + filename = os.path.basename(file) + extension = os.path.splitext(filename)[-1][1:] + if extension != "json" and extension != "wav": + continue + match = re.findall(rf"^{voice}_(\d+)(?:.+?)?{extension}$", filename) + if match and len(match) > 0: + key = int(match[0]) + idx_cache[key] = True + + if len(idx_cache) > 0: + keys = sorted(list(idx_cache.keys())) + idx = keys[-1] + 1 + + idx = pad(idx, 4) + + def get_name(line=0, candidate=0, combined=False): + name = f"{idx}" + if combined: + name = f"{name}_combined" + elif len(texts) > 1: + name = f"{name}_{line}" + if parameters['candidates'] > 1: + name = f"{name}_{candidate}" + return name + + def get_info( voice, settings = None, latents = True ): + info = {} + info.update(parameters) + + info['time'] = time.time()-full_start_time + info['datetime'] = datetime.now().isoformat() + + info['progress'] = None + del info['progress'] + + if info['delimiter'] == "\n": + info['delimiter'] = "\\n" + + if settings is not None: + for k in settings: + if k in info: + info[k] = settings[k] + return info + + INFERENCING = True + for line, cut_text in enumerate(texts): + tqdm_prefix = f'[{str(line+1)}/{str(len(texts))}]' + print(f"{tqdm_prefix} Generating line: {cut_text}") + start_time = time.time() + + # do setting editing + match = re.findall(r'^(\{.+\}) (.+?)$', cut_text) + override = None + if match and len(match) > 0: + match = match[0] + try: + override = json.loads(match[0]) + cut_text = match[1].strip() + except Exception as e: + raise Exception("Prompt settings editing requested, but received invalid JSON") + + name = get_name(line=line, candidate=0) + + settings = get_settings( override=override ) + references = settings['references'] + settings.pop("references") + settings['out_path'] = f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav' + + gen = tts.inference(cut_text, references, **settings ) + + run_time = time.time()-start_time + print(f"Generating line took {run_time} seconds") + + if not isinstance(gen, list): + gen = [gen] + + for j, g in enumerate(gen): + wav, sr = g + name = get_name(line=line, candidate=j) + + settings['text'] = cut_text + settings['time'] = run_time + settings['datetime'] = datetime.now().isoformat() + + # save here in case some error happens mid-batch + #torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', wav.cpu(), sr) + #soundfile.write(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', wav.cpu()[0,0], sr) + wav, sr = torchaudio.load(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + + audio_cache[name] = { + 'audio': wav, + 'settings': get_info(voice=override['voice'] if override and 'voice' in override else voice, settings=settings) + } + + del gen + do_gc() + INFERENCING = False + + for k in audio_cache: + audio = audio_cache[k]['audio'] + + audio, _ = resample(audio, tts.output_sample_rate, args.output_sample_rate) + if volume_adjust is not None: + audio = volume_adjust(audio) + + audio_cache[k]['audio'] = audio + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{k}.wav', audio, args.output_sample_rate) + + output_voices = [] + for candidate in range(parameters['candidates']): + if len(texts) > 1: + audio_clips = [] + for line in range(len(texts)): + name = get_name(line=line, candidate=candidate) + audio = audio_cache[name]['audio'] + audio_clips.append(audio) + + name = get_name(candidate=candidate, combined=True) + audio = torch.cat(audio_clips, dim=-1) + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', audio, args.output_sample_rate) + + audio = audio.squeeze(0).cpu() + audio_cache[name] = { + 'audio': audio, + 'settings': get_info(voice=voice), + 'output': True + } + else: + name = get_name(candidate=candidate) + audio_cache[name]['output'] = True + + + if args.voice_fixer: + if not voicefixer: + notify_progress("Loading voicefix...", progress=progress) + load_voicefixer() + + try: + fixed_cache = {} + for name in tqdm(audio_cache, desc="Running voicefix..."): + del audio_cache[name]['audio'] + if 'output' not in audio_cache[name] or not audio_cache[name]['output']: + continue + + path = f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav' + fixed = f'{outdir}/{cleanup_voice_name(voice)}_{name}_fixed.wav' + voicefixer.restore( + input=path, + output=fixed, + cuda=get_device_name() == "cuda" and args.voice_fixer_use_cuda, + #mode=mode, + ) + + fixed_cache[f'{name}_fixed'] = { + 'settings': audio_cache[name]['settings'], + 'output': True + } + audio_cache[name]['output'] = False + + for name in fixed_cache: + audio_cache[name] = fixed_cache[name] + except Exception as e: + print(e) + print("\nFailed to run Voicefixer") + + for name in audio_cache: + if 'output' not in audio_cache[name] or not audio_cache[name]['output']: + if args.prune_nonfinal_outputs: + audio_cache[name]['pruned'] = True + os.remove(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + continue + + output_voices.append(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + + if not args.embed_output_metadata: + with open(f'{outdir}/{cleanup_voice_name(voice)}_{name}.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(audio_cache[name]['settings'], indent='\t') ) + + if args.embed_output_metadata: + for name in tqdm(audio_cache, desc="Embedding metadata..."): + if 'pruned' in audio_cache[name] and audio_cache[name]['pruned']: + continue + + metadata = music_tag.load_file(f"{outdir}/{cleanup_voice_name(voice)}_{name}.wav") + metadata['lyrics'] = json.dumps(audio_cache[name]['settings']) + metadata.save() + + if sample_voice is not None: + sample_voice = (tts.input_sample_rate, sample_voice.numpy()) + + info = get_info(voice=voice, latents=False) + print(f"Generation took {info['time']} seconds, saved to '{output_voices[0]}'\n") + + info['seed'] = usedSeed + if 'latents' in info: + del info['latents'] + + os.makedirs('./config/', exist_ok=True) + with open(f'./config/generate.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(info, indent='\t') ) + + stats = [ + [ parameters['seed'], "{:.3f}".format(info['time']) ] + ] + + return ( + sample_voice, + output_voices, + stats, + ) + +def generate_tortoise(**kwargs): + parameters = {} + parameters.update(kwargs) + + voice = parameters['voice'] + progress = parameters['progress'] if 'progress' in parameters else None + if parameters['seed'] == 0: + parameters['seed'] = None + + usedSeed = parameters['seed'] + + global args + global tts + + unload_whisper() + unload_voicefixer() + + if not tts: + # should check if it's loading or unloaded, and load it if it's unloaded + if tts_loading: + raise Exception("TTS is still initializing...") + load_tts() + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + do_gc() + + voice_samples = None + conditioning_latents = None + sample_voice = None + + voice_cache = {} + def fetch_voice( voice ): + cache_key = f'{voice}:{tts.autoregressive_model_hash[:8]}' + if cache_key in voice_cache: + return voice_cache[cache_key] + + print(f"Loading voice: {voice} with model {tts.autoregressive_model_hash[:8]}") + sample_voice = None + if voice == "microphone": + if parameters['mic_audio'] is None: + raise Exception("Please provide audio from mic when choosing `microphone` as a voice input") + voice_samples, conditioning_latents = [load_audio(parameters['mic_audio'], tts.input_sample_rate)], None + elif voice == "random": + voice_samples, conditioning_latents = None, tts.get_random_conditioning_latents() + else: + if progress is not None: + notify_progress(f"Loading voice: {voice}", progress=progress) + + voice_samples, conditioning_latents = load_voice(voice, model_hash=tts.autoregressive_model_hash) + + if voice_samples and len(voice_samples) > 0: + if conditioning_latents is None: + conditioning_latents = compute_latents(voice=voice, voice_samples=voice_samples, voice_latents_chunks=parameters['voice_latents_chunks']) + + sample_voice = torch.cat(voice_samples, dim=-1).squeeze().cpu() + voice_samples = None + + voice_cache[cache_key] = (voice_samples, conditioning_latents, sample_voice) + return voice_cache[cache_key] + + def get_settings( override=None ): + settings = { + 'temperature': float(parameters['temperature']), + + 'top_p': float(parameters['top_p']), + 'diffusion_temperature': float(parameters['diffusion_temperature']), + 'length_penalty': float(parameters['length_penalty']), + 'repetition_penalty': float(parameters['repetition_penalty']), + 'cond_free_k': float(parameters['cond_free_k']), + + 'num_autoregressive_samples': parameters['num_autoregressive_samples'], + 'sample_batch_size': args.sample_batch_size, + 'diffusion_iterations': parameters['diffusion_iterations'], + + 'voice_samples': None, + 'conditioning_latents': None, + + 'use_deterministic_seed': parameters['seed'], + 'return_deterministic_state': True, + 'k': parameters['candidates'], + 'diffusion_sampler': parameters['diffusion_sampler'], + 'breathing_room': parameters['breathing_room'], + 'half_p': "Half Precision" in parameters['experimentals'], + 'cond_free': "Conditioning-Free" in parameters['experimentals'], + 'cvvp_amount': parameters['cvvp_weight'], + + 'autoregressive_model': args.autoregressive_model, + 'diffusion_model': args.diffusion_model, + 'tokenizer_json': args.tokenizer_json, + } + + # could be better to just do a ternary on everything above, but i am not a professional + selected_voice = voice + if override is not None: + if 'voice' in override: + selected_voice = override['voice'] + + for k in override: + if k not in settings: + continue + settings[k] = override[k] + + if settings['autoregressive_model'] is not None: + if settings['autoregressive_model'] == "auto": + settings['autoregressive_model'] = deduce_autoregressive_model(selected_voice) + tts.load_autoregressive_model(settings['autoregressive_model']) + + if not args.use_hifigan: + if settings['diffusion_model'] is not None: + if settings['diffusion_model'] == "auto": + settings['diffusion_model'] = deduce_diffusion_model(selected_voice) + tts.load_diffusion_model(settings['diffusion_model']) + + if settings['tokenizer_json'] is not None: + tts.load_tokenizer_json(settings['tokenizer_json']) + + settings['voice_samples'], settings['conditioning_latents'], _ = fetch_voice(voice=selected_voice) + + # clamp it down for the insane users who want this + # it would be wiser to enforce the sample size to the batch size, but this is what the user wants + settings['sample_batch_size'] = args.sample_batch_size + if not settings['sample_batch_size']: + settings['sample_batch_size'] = tts.autoregressive_batch_size + if settings['num_autoregressive_samples'] < settings['sample_batch_size']: + settings['sample_batch_size'] = settings['num_autoregressive_samples'] + + if settings['conditioning_latents'] is not None and len(settings['conditioning_latents']) == 2 and settings['cvvp_amount'] > 0: + print("Requesting weighing against CVVP weight, but voice latents are missing some extra data. Please regenerate your voice latents with 'Slimmer voice latents' unchecked.") + settings['cvvp_amount'] = 0 + + return settings + + if not parameters['delimiter']: + parameters['delimiter'] = "\n" + elif parameters['delimiter'] == "\\n": + parameters['delimiter'] = "\n" + + if parameters['delimiter'] and parameters['delimiter'] != "" and parameters['delimiter'] in parameters['text']: + texts = parameters['text'].split(parameters['delimiter']) + else: + texts = split_and_recombine_text(parameters['text']) + + full_start_time = time.time() + + outdir = f"{args.results_folder}/{voice}/" + os.makedirs(outdir, exist_ok=True) + + audio_cache = {} + + volume_adjust = torchaudio.transforms.Vol(gain=args.output_volume, gain_type="amplitude") if args.output_volume != 1 else None + + idx = 0 + idx_cache = {} + for i, file in enumerate(os.listdir(outdir)): + filename = os.path.basename(file) + extension = os.path.splitext(filename)[-1][1:] + if extension != "json" and extension != "wav": + continue + match = re.findall(rf"^{voice}_(\d+)(?:.+?)?{extension}$", filename) + if match and len(match) > 0: + key = int(match[0]) + idx_cache[key] = True + + if len(idx_cache) > 0: + keys = sorted(list(idx_cache.keys())) + idx = keys[-1] + 1 + + idx = pad(idx, 4) + + def get_name(line=0, candidate=0, combined=False): + name = f"{idx}" + if combined: + name = f"{name}_combined" + elif len(texts) > 1: + name = f"{name}_{line}" + if parameters['candidates'] > 1: + name = f"{name}_{candidate}" + return name + + def get_info( voice, settings = None, latents = True ): + info = {} + info.update(parameters) + + info['time'] = time.time()-full_start_time + info['datetime'] = datetime.now().isoformat() + + info['model'] = tts.autoregressive_model_path + info['model_hash'] = tts.autoregressive_model_hash + + info['progress'] = None + del info['progress'] + + if info['delimiter'] == "\n": + info['delimiter'] = "\\n" + + if settings is not None: + for k in settings: + if k in info: + info[k] = settings[k] + + if 'half_p' in settings and 'cond_free' in settings: + info['experimentals'] = [] + if settings['half_p']: + info['experimentals'].append("Half Precision") + if settings['cond_free']: + info['experimentals'].append("Conditioning-Free") + + if latents and "latents" not in info: + voice = info['voice'] + model_hash = settings["model_hash"][:8] if settings is not None and "model_hash" in settings else tts.autoregressive_model_hash[:8] + + dir = f'{get_voice_dir()}/{voice}/' + latents_path = f'{dir}/cond_latents_{model_hash}.pth' + + if voice == "random" or voice == "microphone": + if args.use_hifigan: + if latents and settings is not None and torch.any(settings['conditioning_latents']): + os.makedirs(dir, exist_ok=True) + torch.save(conditioning_latents, latents_path) + else: + if latents and settings is not None and settings['conditioning_latents']: + os.makedirs(dir, exist_ok=True) + torch.save(conditioning_latents, latents_path) + + if latents_path and os.path.exists(latents_path): + try: + with open(latents_path, 'rb') as f: + info['latents'] = base64.b64encode(f.read()).decode("ascii") + except Exception as e: + pass + + return info + + INFERENCING = True + for line, cut_text in enumerate(texts): + if should_phonemize(): + cut_text = phonemizer( cut_text ) + + if parameters['emotion'] == "Custom": + if parameters['prompt'] and parameters['prompt'].strip() != "": + cut_text = f"[{parameters['prompt']},] {cut_text}" + elif parameters['emotion'] != "None" and parameters['emotion']: + cut_text = f"[I am really {parameters['emotion'].lower()},] {cut_text}" + + tqdm_prefix = f'[{str(line+1)}/{str(len(texts))}]' + print(f"{tqdm_prefix} Generating line: {cut_text}") + start_time = time.time() + + # do setting editing + match = re.findall(r'^(\{.+\}) (.+?)$', cut_text) + override = None + if match and len(match) > 0: + match = match[0] + try: + override = json.loads(match[0]) + cut_text = match[1].strip() + except Exception as e: + raise Exception("Prompt settings editing requested, but received invalid JSON") + + settings = get_settings( override=override ) + print(settings) + try: + if args.use_hifigan: + gen = tts.tts(cut_text, **settings) + else: + gen, additionals = tts.tts(cut_text, **settings ) + parameters['seed'] = additionals[0] + except Exception as e: + raise RuntimeError(f'Possible latent mismatch: click the "(Re)Compute Voice Latents" button and then try again. Error: {e}') + + run_time = time.time()-start_time + print(f"Generating line took {run_time} seconds") + + if not isinstance(gen, list): + gen = [gen] + + for j, g in enumerate(gen): + audio = g.squeeze(0).cpu() + name = get_name(line=line, candidate=j) + + settings['text'] = cut_text + settings['time'] = run_time + settings['datetime'] = datetime.now().isoformat() + if args.tts_backend == "tortoise": + settings['model'] = tts.autoregressive_model_path + settings['model_hash'] = tts.autoregressive_model_hash + + audio_cache[name] = { + 'audio': audio, + 'settings': get_info(voice=override['voice'] if override and 'voice' in override else voice, settings=settings) + } + # save here in case some error happens mid-batch + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', audio, tts.output_sample_rate) + + del gen + do_gc() + INFERENCING = False + + for k in audio_cache: + audio = audio_cache[k]['audio'] + + audio, _ = resample(audio, tts.output_sample_rate, args.output_sample_rate) + if volume_adjust is not None: + audio = volume_adjust(audio) + + audio_cache[k]['audio'] = audio + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{k}.wav', audio, args.output_sample_rate) + + output_voices = [] + for candidate in range(parameters['candidates']): + if len(texts) > 1: + audio_clips = [] + for line in range(len(texts)): + name = get_name(line=line, candidate=candidate) + audio = audio_cache[name]['audio'] + audio_clips.append(audio) + + name = get_name(candidate=candidate, combined=True) + audio = torch.cat(audio_clips, dim=-1) + torchaudio.save(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav', audio, args.output_sample_rate) + + audio = audio.squeeze(0).cpu() + audio_cache[name] = { + 'audio': audio, + 'settings': get_info(voice=voice), + 'output': True + } + else: + name = get_name(candidate=candidate) + audio_cache[name]['output'] = True + + + if args.voice_fixer: + if not voicefixer: + notify_progress("Loading voicefix...", progress=progress) + load_voicefixer() + + try: + fixed_cache = {} + for name in tqdm(audio_cache, desc="Running voicefix..."): + del audio_cache[name]['audio'] + if 'output' not in audio_cache[name] or not audio_cache[name]['output']: + continue + + path = f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav' + fixed = f'{outdir}/{cleanup_voice_name(voice)}_{name}_fixed.wav' + voicefixer.restore( + input=path, + output=fixed, + cuda=get_device_name() == "cuda" and args.voice_fixer_use_cuda, + #mode=mode, + ) + + fixed_cache[f'{name}_fixed'] = { + 'settings': audio_cache[name]['settings'], + 'output': True + } + audio_cache[name]['output'] = False + + for name in fixed_cache: + audio_cache[name] = fixed_cache[name] + except Exception as e: + print(e) + print("\nFailed to run Voicefixer") + + for name in audio_cache: + if 'output' not in audio_cache[name] or not audio_cache[name]['output']: + if args.prune_nonfinal_outputs: + audio_cache[name]['pruned'] = True + os.remove(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + continue + + output_voices.append(f'{outdir}/{cleanup_voice_name(voice)}_{name}.wav') + + if not args.embed_output_metadata: + with open(f'{outdir}/{cleanup_voice_name(voice)}_{name}.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(audio_cache[name]['settings'], indent='\t') ) + + if args.embed_output_metadata: + for name in tqdm(audio_cache, desc="Embedding metadata..."): + if 'pruned' in audio_cache[name] and audio_cache[name]['pruned']: + continue + + metadata = music_tag.load_file(f"{outdir}/{cleanup_voice_name(voice)}_{name}.wav") + metadata['lyrics'] = json.dumps(audio_cache[name]['settings']) + metadata.save() + + if sample_voice is not None: + sample_voice = (tts.input_sample_rate, sample_voice.numpy()) + + info = get_info(voice=voice, latents=False) + print(f"Generation took {info['time']} seconds, saved to '{output_voices[0]}'\n") + + info['seed'] = usedSeed + if 'latents' in info: + del info['latents'] + + os.makedirs('./config/', exist_ok=True) + with open(f'./config/generate.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(info, indent='\t') ) + + stats = [ + [ parameters['seed'], "{:.3f}".format(info['time']) ] + ] + + return ( + sample_voice, + output_voices, + stats, + ) + +def cancel_generate(): + if not INFERENCING: + return + + import tortoise.api + + tortoise.api.STOP_SIGNAL = True + +def hash_file(path, algo="md5", buffer_size=0): + hash = None + if algo == "md5": + hash = hashlib.md5() + elif algo == "sha1": + hash = hashlib.sha1() + else: + raise Exception(f'Unknown hash algorithm specified: {algo}') + + if not os.path.exists(path): + raise Exception(f'Path not found: {path}') + + with open(path, 'rb') as f: + if buffer_size > 0: + while True: + data = f.read(buffer_size) + if not data: + break + hash.update(data) + else: + hash.update(f.read()) + + return "{0}".format(hash.hexdigest()) + +def update_baseline_for_latents_chunks( voice ): + global current_voice + current_voice = voice + + path = f'{get_voice_dir()}/{voice}/' + if not os.path.isdir(path): + return 1 + + dataset_file = f'./training/{voice}/train.txt' + if os.path.exists(dataset_file): + return 0 # 0 will leverage using the LJspeech dataset for computing latents + + files = os.listdir(path) + + total = 0 + total_duration = 0 + + for file in files: + if file[-4:] != ".wav": + continue + + metadata = torchaudio.info(f'{path}/{file}') + duration = metadata.num_frames / metadata.sample_rate + total_duration += duration + total = total + 1 + + + # brain too fried to figure out a better way + if args.autocalculate_voice_chunk_duration_size == 0: + return int(total_duration / total) if total > 0 else 1 + return int(total_duration / args.autocalculate_voice_chunk_duration_size) if total_duration > 0 else 1 + +def compute_latents(voice=None, voice_samples=None, voice_latents_chunks=0, original_ar=False, original_diffusion=False): + global tts + global args + + unload_whisper() + unload_voicefixer() + + if not tts: + if tts_loading: + raise Exception("TTS is still initializing...") + load_tts() + + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + if args.tts_backend == "bark": + tts.create_voice( voice ) + return + + if args.autoregressive_model == "auto": + tts.load_autoregressive_model(deduce_autoregressive_model(voice)) + + if voice: + load_from_dataset = voice_latents_chunks == 0 + + if load_from_dataset: + dataset_path = f'./training/{voice}/train.txt' + if not os.path.exists(dataset_path): + load_from_dataset = False + else: + with open(dataset_path, 'r', encoding="utf-8") as f: + lines = f.readlines() + + print("Leveraging dataset for computing latents") + + voice_samples = [] + max_length = 0 + for line in lines: + filename = f'./training/{voice}/{line.split("|")[0]}' + + waveform = load_audio(filename, 22050) + max_length = max(max_length, waveform.shape[-1]) + voice_samples.append(waveform) + + for i in range(len(voice_samples)): + voice_samples[i] = pad_or_truncate(voice_samples[i], max_length) + + voice_latents_chunks = len(voice_samples) + if voice_latents_chunks == 0: + print("Dataset is empty!") + load_from_dataset = True + if not load_from_dataset: + voice_samples, _ = load_voice(voice, load_latents=False) + + if voice_samples is None: + return + + conditioning_latents = tts.get_conditioning_latents(voice_samples, return_mels=not args.latents_lean_and_mean, slices=voice_latents_chunks, force_cpu=args.force_cpu_for_conditioning_latents, original_ar=original_ar, original_diffusion=original_diffusion) + + if len(conditioning_latents) == 4: + conditioning_latents = (conditioning_latents[0], conditioning_latents[1], conditioning_latents[2], None) + + outfile = f'{get_voice_dir()}/{voice}/cond_latents_{tts.autoregressive_model_hash[:8]}.pth' + torch.save(conditioning_latents, outfile) + print(f'Saved voice latents: {outfile}') + + return conditioning_latents + +# superfluous, but it cleans up some things +class TrainingState(): + def __init__(self, config_path, keep_x_past_checkpoints=0, start=True): + self.killed = False + + self.training_dir = os.path.dirname(config_path) + with open(config_path, 'r') as file: + self.yaml_config = yaml.safe_load(file) + + self.json_config = json.load(open(f"{self.training_dir}/train.json", 'r', encoding="utf-8")) + self.dataset_path = f"{self.training_dir}/train.txt" + with open(self.dataset_path, 'r', encoding="utf-8") as f: + self.dataset_size = len(f.readlines()) + + self.batch_size = self.json_config["batch_size"] + self.save_rate = self.json_config["save_rate"] + + self.epoch = 0 + self.epochs = self.json_config["epochs"] + self.it = 0 + self.its = calc_iterations( self.epochs, self.dataset_size, self.batch_size ) + self.step = 0 + self.steps = int(self.its / self.dataset_size) + self.checkpoint = 0 + self.checkpoints = int((self.its - self.it) / self.save_rate) + + self.gpus = self.json_config['gpus'] + + self.buffer = [] + + self.open_state = False + self.training_started = False + + self.info = {} + + self.it_rate = "" + self.it_rates = 0 + + self.epoch_rate = "" + + self.eta = "?" + self.eta_hhmmss = "?" + + self.nan_detected = False + + self.last_info_check_at = 0 + self.statistics = { + 'loss': [], + 'lr': [], + 'grad_norm': [], + } + self.losses = [] + self.metrics = { + 'step': "", + 'rate': "", + 'loss': "", + } + + self.loss_milestones = [ 1.0, 0.15, 0.05 ] + + if args.tts_backend=="vall-e": + self.valle_last_it = 0 + self.valle_steps = 0 + + if keep_x_past_checkpoints > 0: + self.cleanup_old(keep=keep_x_past_checkpoints) + if start: + self.spawn_process(config_path=config_path, gpus=self.gpus) + + def spawn_process(self, config_path, gpus=1): + if args.tts_backend == "vall-e": + self.cmd = ['deepspeed', f'--num_gpus={gpus}', '--module', 'vall_e.train', f'yaml="{config_path}"'] + else: + self.cmd = ['train.bat', config_path] if os.name == "nt" else ['./train.sh', config_path] + + print("Spawning process: ", " ".join(self.cmd)) + self.process = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + + def parse_metrics(self, data): + if isinstance(data, str): + if line.find('Training Metrics:') >= 0: + data = json.loads(line.split("Training Metrics:")[-1]) + data['mode'] = "training" + elif line.find('Validation Metrics:') >= 0: + data = json.loads(line.split("Validation Metrics:")[-1]) + data['mode'] = "validation" + else: + return + + self.info = data + if 'epoch' in self.info: + self.epoch = int(self.info['epoch']) + if 'it' in self.info: + self.it = int(self.info['it']) + if 'step' in self.info: + self.step = int(self.info['step']) + if 'steps' in self.info: + self.steps = int(self.info['steps']) + + if 'elapsed_time' in self.info: + self.info['iteration_rate'] = self.info['elapsed_time'] + del self.info['elapsed_time'] + + if 'iteration_rate' in self.info: + it_rate = self.info['iteration_rate'] + self.it_rate = f'{"{:.3f}".format(1/it_rate)}it/s' if 0 < it_rate and it_rate < 1 else f'{"{:.3f}".format(it_rate)}s/it' + self.it_rates += it_rate + + if self.it_rates > 0 and self.it * self.steps > 0: + epoch_rate = self.it_rates / self.it * self.steps + self.epoch_rate = f'{"{:.3f}".format(1/epoch_rate)}epoch/s' if 0 < epoch_rate and epoch_rate < 1 else f'{"{:.3f}".format(epoch_rate)}s/epoch' + + try: + self.eta = (self.its - self.it) * (self.it_rates / self.it) + eta = str(timedelta(seconds=int(self.eta))) + self.eta_hhmmss = eta + except Exception as e: + self.eta_hhmmss = "?" + pass + + self.metrics['step'] = [f"{self.epoch}/{self.epochs}"] + if self.epochs != self.its: + self.metrics['step'].append(f"{self.it}/{self.its}") + if self.steps > 1: + self.metrics['step'].append(f"{self.step}/{self.steps}") + self.metrics['step'] = ", ".join(self.metrics['step']) + + if args.tts_backend == "tortoise": + epoch = self.epoch + (self.step / self.steps) + else: + epoch = self.info['epoch'] if 'epoch' in self.info else self.it + + if self.it > 0: + # probably can double for-loop but whatever + keys = { + 'lrs': ['lr'], + 'losses': ['loss_text_ce', 'loss_mel_ce'], + 'accuracies': [], + 'precisions': [], + 'grad_norms': [], + } + if args.tts_backend == "vall-e": + keys['lrs'] = [ + 'ar.lr', 'nar.lr', + ] + keys['losses'] = [ + # 'ar.loss', 'nar.loss', 'ar+nar.loss', + 'ar.loss.nll', 'nar.loss.nll', + ] + + keys['accuracies'] = [ + 'ar.loss.acc', 'nar.loss.acc', + 'ar.stats.acc', 'nar.loss.acc', + ] + keys['precisions'] = [ 'ar.loss.precision', 'nar.loss.precision', ] + keys['grad_norms'] = ['ar.grad_norm', 'nar.grad_norm'] + + for k in keys['lrs']: + if k not in self.info: + continue + + self.statistics['lr'].append({'epoch': epoch, 'it': self.it, 'value': self.info[k], 'type': k}) + + for k in keys['accuracies']: + if k not in self.info: + continue + + self.statistics['loss'].append({'epoch': epoch, 'it': self.it, 'value': self.info[k], 'type': k}) + + for k in keys['precisions']: + if k not in self.info: + continue + + self.statistics['loss'].append({'epoch': epoch, 'it': self.it, 'value': self.info[k], 'type': k}) + + for k in keys['losses']: + if k not in self.info: + continue + + prefix = "" + + if "mode" in self.info and self.info["mode"] == "validation": + prefix = f'{self.info["name"] if "name" in self.info else "val"}_' + + self.statistics['loss'].append({'epoch': epoch, 'it': self.it, 'value': self.info[k], 'type': f'{prefix}{k}' }) + + self.losses.append( self.statistics['loss'][-1] ) + + for k in keys['grad_norms']: + if k not in self.info: + continue + self.statistics['grad_norm'].append({'epoch': epoch, 'it': self.it, 'value': self.info[k], 'type': k}) + + return data + + def get_status(self): + message = None + + self.metrics['rate'] = [] + if self.epoch_rate: + self.metrics['rate'].append(self.epoch_rate) + if self.it_rate and self.epoch_rate[:-7] != self.it_rate[:-4]: + self.metrics['rate'].append(self.it_rate) + self.metrics['rate'] = ", ".join(self.metrics['rate']) + + eta_hhmmss = self.eta_hhmmss if self.eta_hhmmss else "?" + + self.metrics['loss'] = [] + if 'lr' in self.info: + self.metrics['loss'].append(f'LR: {"{:.3e}".format(self.info["lr"])}') + + if len(self.losses) > 0: + self.metrics['loss'].append(f'Loss: {"{:.3f}".format(self.losses[-1]["value"])}') + + if False and len(self.losses) >= 2: + deriv = 0 + accum_length = len(self.losses)//2 # i *guess* this is fine when you think about it + loss_value = self.losses[-1]["value"] + + for i in range(accum_length): + d1_loss = self.losses[accum_length-i-1]["value"] + d2_loss = self.losses[accum_length-i-2]["value"] + dloss = (d2_loss - d1_loss) + + d1_step = self.losses[accum_length-i-1]["it"] + d2_step = self.losses[accum_length-i-2]["it"] + dstep = (d2_step - d1_step) + + if dstep == 0: + continue + + inst_deriv = dloss / dstep + deriv += inst_deriv + + deriv = deriv / accum_length + + print("Deriv: ", deriv) + + if deriv != 0: # dloss < 0: + next_milestone = None + for milestone in self.loss_milestones: + if loss_value > milestone: + next_milestone = milestone + break + + print(f"Loss value: {loss_value} | Next milestone: {next_milestone} | Distance: {loss_value - next_milestone}") + + if next_milestone: + # tfw can do simple calculus but not basic algebra in my head + est_its = (next_milestone - loss_value) / deriv * 100 + print(f"Estimated: {est_its}") + if est_its >= 0: + self.metrics['loss'].append(f'Est. milestone {next_milestone} in: {int(est_its)}its') + else: + est_loss = inst_deriv * (self.its - self.it) + loss_value + if est_loss >= 0: + self.metrics['loss'].append(f'Est. final loss: {"{:.3f}".format(est_loss)}') + + self.metrics['loss'] = ", ".join(self.metrics['loss']) + + message = f"[{self.metrics['step']}] [{self.metrics['rate']}] [ETA: {eta_hhmmss}] [{self.metrics['loss']}]" + if self.nan_detected: + message = f"[!NaN DETECTED! {self.nan_detected}] {message}" + + return message + + def load_statistics(self, update=False): + if not os.path.isdir(self.training_dir): + return + + if args.tts_backend == "tortoise": + logs = sorted([f'{self.training_dir}/finetune/{d}' for d in os.listdir(f'{self.training_dir}/finetune/') if d[-4:] == ".log" ]) + else: + log_dir = "logs" + logs = sorted([f'{self.training_dir}/{log_dir}/{d}/log.txt' for d in os.listdir(f'{self.training_dir}/{log_dir}/') ]) + + if update: + logs = [logs[-1]] + + infos = {} + highest_step = self.last_info_check_at + + if not update: + self.statistics['loss'] = [] + self.statistics['lr'] = [] + self.statistics['grad_norm'] = [] + self.it_rates = 0 + + unq = {} + averager = None + prev_state = 0 + + for log in logs: + with open(log, 'r', encoding="utf-8") as f: + lines = f.readlines() + + for line in lines: + line = line.strip() + if not line: + continue + + if line[-1] == ".": + line = line[:-1] + + if line.find('Training Metrics:') >= 0: + split = line.split("Training Metrics:")[-1] + data = json.loads(split) + + name = "train" + mode = "training" + prev_state = 0 + elif line.find('Validation Metrics:') >= 0: + data = json.loads(line.split("Validation Metrics:")[-1]) + if "it" not in data: + data['it'] = it + if "epoch" not in data: + data['epoch'] = epoch + + # name = data['name'] if 'name' in data else "val" + mode = "validation" + + if prev_state == 0: + name = "subtrain" + else: + name = "val" + + prev_state += 1 + else: + continue + + if "it" not in data: + continue + + it = data['it'] + epoch = data['epoch'] + + if args.tts_backend == "vall-e": + if not averager or averager['key'] != f'{it}_{name}' or averager['mode'] != mode: + averager = { + 'key': f'{it}_{name}', + 'name': name, + 'mode': mode, + "metrics": {} + } + for k in data: + if data[k] is None: + continue + averager['metrics'][k] = [ data[k] ] + else: + for k in data: + if data[k] is None: + continue + if k not in averager['metrics']: + averager['metrics'][k] = [ data[k] ] + else: + averager['metrics'][k].append( data[k] ) + + unq[f'{it}_{mode}_{name}'] = averager + else: + unq[f'{it}_{mode}_{name}'] = data + + if update and it <= self.last_info_check_at: + continue + + blacklist = [ "batch", "eval" ] + for it in unq: + if args.tts_backend == "vall-e": + stats = unq[it] + data = {k: sum(v) / len(v) for k, v in stats['metrics'].items() if k not in blacklist } + #data = {k: min(v) for k, v in stats['metrics'].items() if k not in blacklist } + #data = {k: max(v) for k, v in stats['metrics'].items() if k not in blacklist } + data['name'] = stats['name'] + data['mode'] = stats['mode'] + data['steps'] = len(stats['metrics']['it']) + else: + data = unq[it] + self.parse_metrics(data) + + self.last_info_check_at = highest_step + + def cleanup_old(self, keep=2): + if keep <= 0: + return + + if args.tts_backend == "vall-e": + return + + if not os.path.isdir(f'{self.training_dir}/finetune/'): + return + + models = sorted([ int(d[:-8]) for d in os.listdir(f'{self.training_dir}/finetune/models/') if d[-8:] == "_gpt.pth" ]) + states = sorted([ int(d[:-6]) for d in os.listdir(f'{self.training_dir}/finetune/training_state/') if d[-6:] == ".state" ]) + remove_models = models[:-keep] + remove_states = states[:-keep] + + for d in remove_models: + path = f'{self.training_dir}/finetune/models/{d}_gpt.pth' + print("Removing", path) + os.remove(path) + for d in remove_states: + path = f'{self.training_dir}/finetune/training_state/{d}.state' + print("Removing", path) + os.remove(path) + + def parse(self, line, verbose=False, keep_x_past_checkpoints=0, buffer_size=8, progress=None ): + self.buffer.append(f'{line}') + + data = None + percent = 0 + message = None + should_return = False + + MESSAGE_START = 'Start training from epoch' + MESSAGE_FINSIHED = 'Finished training' + MESSAGE_SAVING = 'Saving models and training states.' + + MESSAGE_METRICS_TRAINING = 'Training Metrics:' + MESSAGE_METRICS_VALIDATION = 'Validation Metrics:' + + if line.find(MESSAGE_FINSIHED) >= 0: + self.killed = True + # rip out iteration info + elif not self.training_started: + if line.find(MESSAGE_START) >= 0: + self.training_started = True # could just leverage the above variable, but this is python, and there's no point in these aggressive microoptimizations + + match = re.findall(r'epoch: ([\d,]+)', line) + if match and len(match) > 0: + self.epoch = int(match[0].replace(",", "")) + match = re.findall(r'iter: ([\d,]+)', line) + if match and len(match) > 0: + self.it = int(match[0].replace(",", "")) + + self.checkpoints = int((self.its - self.it) / self.save_rate) + + self.load_statistics() + + should_return = True + else: + if line.find(MESSAGE_SAVING) >= 0: + self.checkpoint += 1 + message = f"[{self.checkpoint}/{self.checkpoints}] Saving checkpoint..." + percent = self.checkpoint / self.checkpoints + + self.cleanup_old(keep=keep_x_past_checkpoints) + elif line.find(MESSAGE_METRICS_TRAINING) >= 0: + data = json.loads(line.split(MESSAGE_METRICS_TRAINING)[-1]) + data['mode'] = "training" + elif line.find(MESSAGE_METRICS_VALIDATION) >= 0: + data = json.loads(line.split(MESSAGE_METRICS_VALIDATION)[-1]) + data['mode'] = "validation" + + if data is not None: + if ': nan' in line and not self.nan_detected: + self.nan_detected = self.it + + self.parse_metrics( data ) + message = self.get_status() + + if message: + percent = self.it / float(self.its) # self.epoch / float(self.epochs) + if progress is not None: + progress(percent, message) + + self.buffer.append(f'[{"{:.3f}".format(percent*100)}%] {message}') + should_return = True + + if verbose and not self.training_started: + should_return = True + + self.buffer = self.buffer[-buffer_size:] + + result = None + if should_return: + result = "".join(self.buffer) if not self.training_started else message + + return ( + result, + percent, + message, + ) + +try: + import altair as alt + alt.data_transformers.enable('default', max_rows=None) +except Exception as e: + print(e) + pass + +def run_training(config_path, verbose=False, keep_x_past_checkpoints=0, progress=gr.Progress(track_tqdm=True)): + global training_state + if training_state and training_state.process: + return "Training already in progress" + + + # ensure we have the dvae.pth + if args.tts_backend == "tortoise": + get_model_path('dvae.pth') + + # I don't know if this is still necessary, as it was bitching at me for not doing this, despite it being in a separate process + torch.multiprocessing.freeze_support() + + unload_tts() + unload_whisper() + unload_voicefixer() + + training_state = TrainingState(config_path=config_path, keep_x_past_checkpoints=keep_x_past_checkpoints) + + for line in iter(training_state.process.stdout.readline, ""): + if training_state is None or training_state.killed: + return + + result, percent, message = training_state.parse( line=line, verbose=verbose, keep_x_past_checkpoints=keep_x_past_checkpoints, progress=progress ) + print(f"[Training] [{datetime.now().isoformat()}] {line[:-1]}") + if result: + yield result + + if progress is not None and message: + progress(percent, message) + + if training_state: + training_state.process.stdout.close() + return_code = training_state.process.wait() + training_state = None + +def update_training_dataplot(x_min=None, x_max=None, y_min=None, y_max=None, config_path=None): + global training_state + losses = None + lrs = None + grad_norms = None + + x_lim = [ x_min, x_max ] + y_lim = [ y_min, y_max ] + + if not training_state: + if config_path: + training_state = TrainingState(config_path=config_path, start=False) + training_state.load_statistics() + message = training_state.get_status() + + if training_state: + if not x_lim[-1]: + x_lim[-1] = training_state.epochs + + if not y_lim[-1]: + y_lim = None + + if len(training_state.statistics['loss']) > 0: + losses = gr.LinePlot.update( + value = pd.DataFrame(training_state.statistics['loss']), + x_lim=x_lim, y_lim=y_lim, + x="epoch", y="value", # x="it", + title="Loss Metrics", color="type", tooltip=['epoch', 'it', 'value', 'type'], + width=500, height=350 + ) + if len(training_state.statistics['lr']) > 0: + lrs = gr.LinePlot.update( + value = pd.DataFrame(training_state.statistics['lr']), + x_lim=x_lim, + x="epoch", y="value", # x="it", + title="Learning Rate", color="type", tooltip=['epoch', 'it', 'value', 'type'], + width=500, height=350 + ) + if len(training_state.statistics['grad_norm']) > 0: + grad_norms = gr.LinePlot.update( + value = pd.DataFrame(training_state.statistics['grad_norm']), + x_lim=x_lim, + x="epoch", y="value", # x="it", + title="Gradient Normals", color="type", tooltip=['epoch', 'it', 'value', 'type'], + width=500, height=350 + ) + + if config_path: + del training_state + training_state = None + + return (losses, lrs, grad_norms) + +def reconnect_training(verbose=False, progress=gr.Progress(track_tqdm=True)): + global training_state + if not training_state or not training_state.process: + return "Training not in progress" + + for line in iter(training_state.process.stdout.readline, ""): + result, percent, message = training_state.parse( line=line, verbose=verbose, progress=progress ) + print(f"[Training] [{datetime.now().isoformat()}] {line[:-1]}") + if result: + yield result + + if progress is not None and message: + progress(percent, message) + +def stop_training(): + global training_state + if training_state is None: + return "No training in progress" + print("Killing training process...") + training_state.killed = True + + children = [] + if args.tts_backend == "tortoise": + # wrapped in a try/catch in case for some reason this fails outside of Linux + try: + children = [p.info for p in psutil.process_iter(attrs=['pid', 'name', 'cmdline']) if './src/train.py' in p.info['cmdline']] + except Exception as e: + pass + + training_state.process.stdout.close() + training_state.process.terminate() + training_state.process.kill() + elif args.tts_backend == "vall-e": + print(training_state.process.communicate(input='quit')[0]) + + return_code = training_state.process.wait() + + for p in children: + os.kill( p['pid'], signal.SIGKILL ) + + training_state = None + print("Killed training process.") + return f"Training cancelled: {return_code}" + +def get_halfp_model_path(): + autoregressive_model_path = get_model_path('autoregressive.pth') + return autoregressive_model_path.replace(".pth", "_half.pth") + +def convert_to_halfp(): + autoregressive_model_path = get_model_path('autoregressive.pth') + print(f'Converting model to half precision: {autoregressive_model_path}') + model = torch.load(autoregressive_model_path) + for k in model: + model[k] = model[k].half() + + outfile = get_halfp_model_path() + torch.save(model, outfile) + print(f'Converted model to half precision: {outfile}') + + +# collapses short segments into the previous segment +def whisper_sanitize( results ): + sanitized = json.loads(json.dumps(results)) + sanitized['segments'] = [] + + for segment in results['segments']: + length = segment['end'] - segment['start'] + if length >= MIN_TRAINING_DURATION or len(sanitized['segments']) == 0: + sanitized['segments'].append(segment) + continue + + last_segment = sanitized['segments'][-1] + # segment already asimilitated it, somehow + if last_segment['end'] >= segment['end']: + continue + """ + # segment already asimilitated it, somehow + if last_segment['text'].endswith(segment['text']): + continue + """ + last_segment['text'] += segment['text'] + last_segment['end'] = segment['end'] + + for i in range(len(sanitized['segments'])): + sanitized['segments'][i]['id'] = i + + return sanitized + +def whisper_transcribe( file, language=None ): + # shouldn't happen, but it's for safety + global whisper_model + global whisper_align_model + + if not whisper_model: + load_whisper_model(language=language) + + if args.whisper_backend == "openai/whisper": + if not language: + language = None + + return whisper_model.transcribe(file, language=language) + + if args.whisper_backend == "lightmare/whispercpp": + res = whisper_model.transcribe(file) + segments = whisper_model.extract_text_and_timestamps( res ) + + result = { + 'text': [], + 'segments': [] + } + for segment in segments: + reparsed = { + 'start': segment[0] / 100.0, + 'end': segment[1] / 100.0, + 'text': segment[2], + 'id': len(result['segments']) + } + result['text'].append( segment[2] ) + result['segments'].append(reparsed) + + result['text'] = " ".join(result['text']) + return result + + if args.whisper_backend == "m-bain/whisperx": + import whisperx + + device = "cuda" if get_device_name() == "cuda" else "cpu" + result = whisper_model.transcribe(file, batch_size=args.whisper_batchsize) + + align_model, metadata = whisper_align_model + result_aligned = whisperx.align(result["segments"], align_model, metadata, file, device, return_char_alignments=False) + + result['segments'] = result_aligned['segments'] + result['text'] = [] + for segment in result['segments']: + segment['id'] = len(result['text']) + result['text'].append(segment['text'].strip()) + result['text'] = " ".join(result['text']) + + return result + +def validate_waveform( waveform, sample_rate, min_only=False ): + if not torch.any(waveform < 0): + return "Waveform is empty" + + num_channels, num_frames = waveform.shape + duration = num_frames / sample_rate + + if duration < MIN_TRAINING_DURATION: + return "Duration too short ({:.3f}s < {:.3f}s)".format(duration, MIN_TRAINING_DURATION) + + if not min_only: + if duration > MAX_TRAINING_DURATION: + return "Duration too long ({:.3f}s < {:.3f}s)".format(MAX_TRAINING_DURATION, duration) + + return + +def transcribe_dataset( voice, language=None, skip_existings=False, progress=None ): + unload_tts() + + global whisper_model + if whisper_model is None: + load_whisper_model(language=language) + + results = {} + + files = get_voice(voice, load_latents=False) + indir = f'./training/{voice}/' + infile = f'{indir}/whisper.json' + + quantize_in_memory = args.tts_backend == "vall-e" + + os.makedirs(f'{indir}/audio/', exist_ok=True) + + TARGET_SAMPLE_RATE = 22050 + if args.tts_backend != "tortoise": + TARGET_SAMPLE_RATE = 24000 + if tts: + TARGET_SAMPLE_RATE = tts.input_sample_rate + + if os.path.exists(infile): + results = json.load(open(infile, 'r', encoding="utf-8")) + + for file in tqdm(files, desc="Iterating through voice files"): + basename = os.path.basename(file) + + if basename in results and skip_existings: + print(f"Skipping already parsed file: {basename}") + continue + + try: + result = whisper_transcribe(file, language=language) + except Exception as e: + print("Failed to transcribe:", file, e) + continue + + results[basename] = result + + if not quantize_in_memory: + waveform, sample_rate = torchaudio.load(file) + # resample to the input rate, since it'll get resampled for training anyways + # this should also "help" increase throughput a bit when filling the dataloaders + waveform, sample_rate = resample(waveform, sample_rate, TARGET_SAMPLE_RATE) + if waveform.shape[0] == 2: + waveform = waveform[:1] + + try: + kwargs = {} + if basename[-4:] == ".wav": + kwargs['encoding'] = "PCM_S" + kwargs['bits_per_sample'] = 16 + + torchaudio.save(f"{indir}/audio/{basename}", waveform, sample_rate, **kwargs) + except Exception as e: + print(e) + + with open(infile, 'w', encoding="utf-8") as f: + f.write(json.dumps(results, indent='\t')) + + do_gc() + + modified = False + for basename in results: + try: + sanitized = whisper_sanitize(results[basename]) + if len(sanitized['segments']) > 0 and len(sanitized['segments']) != len(results[basename]['segments']): + results[basename] = sanitized + modified = True + print("Segments sanizited: ", basename) + except Exception as e: + print("Failed to sanitize:", basename, e) + pass + + if modified: + os.rename(infile, infile.replace(".json", ".unsanitized.json")) + with open(infile, 'w', encoding="utf-8") as f: + f.write(json.dumps(results, indent='\t')) + + return f"Processed dataset to: {indir}" + +def slice_waveform( waveform, sample_rate, start, end, trim ): + start = int(start * sample_rate) + end = int(end * sample_rate) + + if start < 0: + start = 0 + if end >= waveform.shape[-1]: + end = waveform.shape[-1] - 1 + + sliced = waveform[:, start:end] + + error = validate_waveform( sliced, sample_rate, min_only=True ) + if trim and not error: + sliced = torchaudio.functional.vad( sliced, sample_rate ) + + return sliced, error + +def slice_dataset( voice, trim_silence=True, start_offset=0, end_offset=0, results=None, progress=gr.Progress() ): + indir = f'./training/{voice}/' + infile = f'{indir}/whisper.json' + messages = [] + + if not os.path.exists(infile): + message = f"Missing dataset: {infile}" + print(message) + return message + + if results is None: + results = json.load(open(infile, 'r', encoding="utf-8")) + + TARGET_SAMPLE_RATE = 22050 + if args.tts_backend != "tortoise": + TARGET_SAMPLE_RATE = 24000 + if tts: + TARGET_SAMPLE_RATE = tts.input_sample_rate + + files = 0 + segments = 0 + for filename in results: + path = f'./voices/{voice}/{filename}' + extension = os.path.splitext(filename)[-1][1:] + out_extension = extension # "wav" + + if not os.path.exists(path): + path = f'./training/{voice}/{filename}' + + if not os.path.exists(path): + message = f"Missing source audio: {filename}" + print(message) + messages.append(message) + continue + + files += 1 + result = results[filename] + waveform, sample_rate = torchaudio.load(path) + num_channels, num_frames = waveform.shape + duration = num_frames / sample_rate + + for segment in result['segments']: + file = filename.replace(f".{extension}", f"_{pad(segment['id'], 4)}.{out_extension}") + + sliced, error = slice_waveform( waveform, sample_rate, segment['start'] + start_offset, segment['end'] + end_offset, trim_silence ) + if error: + message = f"{error}, skipping... {file}" + print(message) + messages.append(message) + continue + + sliced, _ = resample( sliced, sample_rate, TARGET_SAMPLE_RATE ) + + if waveform.shape[0] == 2: + waveform = waveform[:1] + + kwargs = {} + if file[-4:] == ".wav": + kwargs['encoding'] = "PCM_S" + kwargs['bits_per_sample'] = 16 + + torchaudio.save(f"{indir}/audio/{file}", sliced, TARGET_SAMPLE_RATE, **kwargs) + + segments +=1 + + messages.append(f"Sliced segments: {files} => {segments}.") + return "\n".join(messages) + +# takes an LJSpeech-dataset-formatted .txt file and phonemize it +def phonemize_txt_file( path ): + with open(path, 'r', encoding='utf-8') as f: + lines = f.readlines() + + reparsed = [] + with open(path.replace(".txt", ".phn.txt"), 'a', encoding='utf-8') as f: + for line in tqdm(lines, desc='Phonemizing...'): + split = line.split("|") + audio = split[0] + text = split[2] + + phonemes = phonemizer( text ) + reparsed.append(f'{audio}|{phonemes}') + f.write(f'\n{audio}|{phonemes}') + + + joined = "\n".join(reparsed) + with open(path.replace(".txt", ".phn.txt"), 'w', encoding='utf-8') as f: + f.write(joined) + + return joined + +# takes an LJSpeech-dataset-formatted .txt (and phonemized .phn.txt from the above) and creates a JSON that should slot in as whisper.json +def create_dataset_json( path ): + with open(path, 'r', encoding='utf-8') as f: + lines = f.readlines() + + phonemes = None + phn_path = path.replace(".txt", ".phn.txt") + if os.path.exists(phn_path): + with open(phn_path, 'r', encoding='utf-8') as f: + phonemes = f.readlines() + + data = {} + + for line in lines: + split = line.split("|") + audio = split[0] + text = split[1] + + data[audio] = { + 'text': text.strip() + } + + for line in phonemes: + split = line.split("|") + audio = split[0] + text = split[1] + + data[audio]['phonemes'] = text.strip() + + with open(path.replace(".txt", ".json"), 'w', encoding='utf-8') as f: + f.write(json.dumps(data, indent="\t")) + + +cached_backends = {} + +def phonemizer( text, language="en-us" ): + from phonemizer import phonemize + from phonemizer.backend import BACKENDS + + def _get_backend( language="en-us", backend="espeak" ): + key = f'{language}_{backend}' + if key in cached_backends: + return cached_backends[key] + + if backend == 'espeak': + phonemizer = BACKENDS[backend]( language, preserve_punctuation=True, with_stress=True) + elif backend == 'espeak-mbrola': + phonemizer = BACKENDS[backend]( language ) + else: + phonemizer = BACKENDS[backend]( language, preserve_punctuation=True ) + + cached_backends[key] = phonemizer + return phonemizer + if language == "en": + language = "en-us" + + backend = _get_backend(language=language, backend=args.phonemizer_backend) + if backend is not None: + tokens = backend.phonemize( [text], strip=True ) + else: + tokens = phonemize( [text], language=language, strip=True, preserve_punctuation=True, with_stress=True ) + + return tokens[0] if len(tokens) == 0 else tokens + tokenized = " ".join( tokens ) + +def should_phonemize(): + if args.tts_backend == "vall-e": + return False + + should = args.tokenizer_json is not None and args.tokenizer_json[-8:] == "ipa.json" + if should: + try: + from phonemizer import phonemize + except Exception as e: + return False + return should + +def prepare_dataset( voice, use_segments=False, text_length=0, audio_length=0, progress=gr.Progress() ): + indir = f'./training/{voice}/' + infile = f'{indir}/whisper.json' + if not os.path.exists(infile): + message = f"Missing dataset: {infile}" + print(message) + return message + + results = json.load(open(infile, 'r', encoding="utf-8")) + + errored = 0 + messages = [] + normalize = False # True + phonemize = should_phonemize() + lines = { 'training': [], 'validation': [] } + segments = {} + + quantize_in_memory = args.tts_backend == "vall-e" + + if args.tts_backend != "tortoise": + text_length = 0 + audio_length = 0 + + start_offset = -0.1 + end_offset = 0.1 + trim_silence = False + + TARGET_SAMPLE_RATE = 22050 + if args.tts_backend != "tortoise": + TARGET_SAMPLE_RATE = 24000 + if tts: + TARGET_SAMPLE_RATE = tts.input_sample_rate + + for filename in tqdm(results, desc="Parsing results"): + use_segment = use_segments + + extension = os.path.splitext(filename)[-1][1:] + out_extension = extension # "wav" + result = results[filename] + lang = result['language'] + language = LANGUAGES[lang] if lang in LANGUAGES else lang + normalizer = EnglishTextNormalizer() if language and language == "english" else BasicTextNormalizer() + + # check if unsegmented text exceeds 200 characters + if not use_segment: + if len(result['text']) > MAX_TRAINING_CHAR_LENGTH: + message = f"Text length too long ({MAX_TRAINING_CHAR_LENGTH} < {len(result['text'])}), using segments: {filename}" + print(message) + messages.append(message) + use_segment = True + + # check if unsegmented audio exceeds 11.6s + if not use_segment: + path = f'{indir}/audio/{filename}' + if not quantize_in_memory and not os.path.exists(path): + messages.append(f"Missing source audio: {filename}") + errored += 1 + continue + + duration = 0 + for segment in result['segments']: + duration = max(duration, segment['end']) + + if duration >= MAX_TRAINING_DURATION: + message = f"Audio too large, using segments: {filename}" + print(message) + messages.append(message) + use_segment = True + + # implicitly segment + if use_segment and not use_segments: + exists = True + for segment in result['segments']: + duration = segment['end'] - segment['start'] + if duration <= MIN_TRAINING_DURATION or MAX_TRAINING_DURATION <= duration: + continue + + path = f'{indir}/audio/' + filename.replace(f".{extension}", f"_{pad(segment['id'], 4)}.{out_extension}") + if os.path.exists(path): + continue + exists = False + break + + if not quantize_in_memory and not exists: + tmp = {} + tmp[filename] = result + print(f"Audio not segmented, segmenting: {filename}") + message = slice_dataset( voice, results=tmp ) + print(message) + messages = messages + message.split("\n") + + waveform = None + + + if quantize_in_memory: + path = f'{indir}/audio/{filename}' + if not os.path.exists(path): + path = f'./voices/{voice}/{filename}' + + if not os.path.exists(path): + message = f"Audio not found: {path}" + print(message) + messages.append(message) + #continue + else: + waveform = torchaudio.load(path) + waveform = resample(waveform[0], waveform[1], TARGET_SAMPLE_RATE) + + if not use_segment: + segments[filename] = { + 'text': result['text'], + 'lang': lang, + 'language': language, + 'normalizer': normalizer, + 'phonemes': result['phonemes'] if 'phonemes' in result else None + } + + if waveform: + segments[filename]['waveform'] = waveform + else: + for segment in result['segments']: + duration = segment['end'] - segment['start'] + if duration <= MIN_TRAINING_DURATION or MAX_TRAINING_DURATION <= duration: + continue + + file = filename.replace(f".{extension}", f"_{pad(segment['id'], 4)}.{out_extension}") + + segments[file] = { + 'text': segment['text'], + 'lang': lang, + 'language': language, + 'normalizer': normalizer, + 'phonemes': segment['phonemes'] if 'phonemes' in segment else None + } + + if waveform: + sliced, error = slice_waveform( waveform[0], waveform[1], segment['start'] + start_offset, segment['end'] + end_offset, trim_silence ) + if error: + message = f"{error}, skipping... {file}" + print(message) + messages.append(message) + segments[file]['error'] = error + #continue + else: + segments[file]['waveform'] = (sliced, waveform[1]) + + jobs = { + 'quantize': [[], []], + 'phonemize': [[], []], + } + + for file in tqdm(segments, desc="Parsing segments"): + extension = os.path.splitext(file)[-1][1:] + result = segments[file] + path = f'{indir}/audio/{file}' + + text = result['text'] + lang = result['lang'] + language = result['language'] + normalizer = result['normalizer'] + phonemes = result['phonemes'] + if phonemize and phonemes is None: + phonemes = phonemizer( text, language=lang ) + + normalized = normalizer(text) if normalize else text + + if len(text) > MAX_TRAINING_CHAR_LENGTH: + message = f"Text length too long ({MAX_TRAINING_CHAR_LENGTH} < {len(text)}), skipping... {file}" + print(message) + messages.append(message) + errored += 1 + continue + + # num_channels, num_frames = waveform.shape + #duration = num_frames / sample_rate + + + culled = len(text) < text_length + if not culled and audio_length > 0: + culled = duration < audio_length + + line = f'audio/{file}|{phonemes if phonemize and phonemes else text}' + + lines['training' if not culled else 'validation'].append(line) + + if culled or args.tts_backend != "vall-e": + continue + + os.makedirs(f'{indir}/valle/', exist_ok=True) + #os.makedirs(f'./training/valle/data/{voice}/', exist_ok=True) + + phn_file = f'{indir}/valle/{file.replace(f".{extension}",".phn.txt")}' + #phn_file = f'./training/valle/data/{voice}/{file.replace(f".{extension}",".phn.txt")}' + if not os.path.exists(phn_file): + jobs['phonemize'][0].append(phn_file) + jobs['phonemize'][1].append(normalized) + """ + phonemized = valle_phonemize( normalized ) + open(f'{indir}/valle/{file.replace(".wav",".phn.txt")}', 'w', encoding='utf-8').write(" ".join(phonemized)) + print("Phonemized:", file, normalized, text) + """ + + qnt_file = f'{indir}/valle/{file.replace(f".{extension}",".qnt.pt")}' + #qnt_file = f'./training/valle/data/{voice}/{file.replace(f".{extension}",".qnt.pt")}' + if 'error' not in result: + if not quantize_in_memory and not os.path.exists(path): + message = f"Missing segment, skipping... {file}" + print(message) + messages.append(message) + errored += 1 + continue + + if not os.path.exists(qnt_file): + waveform = None + if 'waveform' in result: + waveform, sample_rate = result['waveform'] + elif os.path.exists(path): + waveform, sample_rate = torchaudio.load(path) + error = validate_waveform( waveform, sample_rate ) + if error: + message = f"{error}, skipping... {file}" + print(message) + messages.append(message) + errored += 1 + continue + + if waveform is not None: + jobs['quantize'][0].append(qnt_file) + jobs['quantize'][1].append((waveform, sample_rate)) + """ + quantized = valle_quantize( waveform, sample_rate ).cpu() + torch.save(quantized, f'{indir}/valle/{file.replace(".wav",".qnt.pt")}') + print("Quantized:", file) + """ + + for i in tqdm(range(len(jobs['quantize'][0])), desc="Quantizing"): + qnt_file = jobs['quantize'][0][i] + waveform, sample_rate = jobs['quantize'][1][i] + + quantized = valle_quantize( waveform, sample_rate ).cpu() + torch.save(quantized, qnt_file) + #print("Quantized:", qnt_file) + + for i in tqdm(range(len(jobs['phonemize'][0])), desc="Phonemizing"): + phn_file = jobs['phonemize'][0][i] + normalized = jobs['phonemize'][1][i] + + if language == "japanese": + language = "ja" + + if language == "ja" and PYKAKASI_ENABLED and KKS is not None: + normalized = KKS.convert(normalized) + normalized = [ n["hira"] for n in normalized ] + normalized = "".join(normalized) + + try: + phonemized = valle_phonemize( normalized ) + open(phn_file, 'w', encoding='utf-8').write(" ".join(phonemized)) + #print("Phonemized:", phn_file) + except Exception as e: + message = f"Failed to phonemize: {phn_file}: {normalized}" + messages.append(message) + print(message) + + + training_joined = "\n".join(lines['training']) + validation_joined = "\n".join(lines['validation']) + + with open(f'{indir}/train.txt', 'w', encoding="utf-8") as f: + f.write(training_joined) + + with open(f'{indir}/validation.txt', 'w', encoding="utf-8") as f: + f.write(validation_joined) + + messages.append(f"Prepared {len(lines['training'])} lines (validation: {len(lines['validation'])}, culled: {errored}).\n{training_joined}\n\n{validation_joined}") + return "\n".join(messages) + +def calc_iterations( epochs, lines, batch_size ): + return int(math.ceil(epochs * math.ceil(lines / batch_size))) + +def schedule_learning_rate( iterations, schedule=LEARNING_RATE_SCHEDULE ): + return [int(iterations * d) for d in schedule] + +def optimize_training_settings( **kwargs ): + messages = [] + settings = {} + settings.update(kwargs) + + dataset_path = f"./training/{settings['voice']}/train.txt" + with open(dataset_path, 'r', encoding="utf-8") as f: + lines = len(f.readlines()) + + if lines == 0: + raise Exception("Empty dataset.") + + if settings['batch_size'] > lines: + settings['batch_size'] = lines + messages.append(f"Batch size is larger than your dataset, clamping batch size to: {settings['batch_size']}") + + """ + if lines % settings['batch_size'] != 0: + settings['batch_size'] = int(lines / settings['batch_size']) + if settings['batch_size'] == 0: + settings['batch_size'] = 1 + messages.append(f"Batch size not neatly divisible by dataset size, adjusting batch size to: {settings['batch_size']}") + """ + if settings['gradient_accumulation_size'] == 0: + settings['gradient_accumulation_size'] = 1 + + if settings['batch_size'] / settings['gradient_accumulation_size'] < 2: + settings['gradient_accumulation_size'] = int(settings['batch_size'] / 2) + if settings['gradient_accumulation_size'] == 0: + settings['gradient_accumulation_size'] = 1 + + messages.append(f"Gradient accumulation size is too large for a given batch size, clamping gradient accumulation size to: {settings['gradient_accumulation_size']}") + elif settings['batch_size'] % settings['gradient_accumulation_size'] != 0: + settings['gradient_accumulation_size'] -= settings['batch_size'] % settings['gradient_accumulation_size'] + if settings['gradient_accumulation_size'] == 0: + settings['gradient_accumulation_size'] = 1 + + messages.append(f"Batch size is not evenly divisible by the gradient accumulation size, adjusting gradient accumulation size to: {settings['gradient_accumulation_size']}") + + if settings['batch_size'] % settings['gpus'] != 0: + settings['batch_size'] -= settings['batch_size'] % settings['gpus'] + if settings['batch_size'] == 0: + settings['batch_size'] = 1 + messages.append(f"Batch size not neatly divisible by GPU count, adjusting batch size to: {settings['batch_size']}") + + + def get_device_batch_size( vram ): + DEVICE_BATCH_SIZE_MAP = [ + (70, 128), # based on an A100-80G, I can safely get a ratio of 4096:32 = 128 + (32, 64), # based on my two 6800XTs, I can only really safely get a ratio of 128:2 = 64 + (16, 8), # based on an A4000, I can do a ratio of 512:64 = 8:1 + (8, 4), # interpolated + (6, 2), # based on my 2060, it only really lets me have a batch ratio of 2:1 + ] + for k, v in DEVICE_BATCH_SIZE_MAP: + if vram > (k-1): + return v + return 1 + + if settings['gpus'] > get_device_count(): + settings['gpus'] = get_device_count() + messages.append(f"GPU count exceeds defacto GPU count, clamping to: {settings['gpus']}") + + if settings['gpus'] <= 1: + settings['gpus'] = 1 + else: + messages.append(f"! EXPERIMENTAL ! Multi-GPU training is extremely particular, expect issues.") + + # assuming you have equal GPUs + vram = get_device_vram() * settings['gpus'] + batch_ratio = int(settings['batch_size'] / settings['gradient_accumulation_size']) + batch_cap = get_device_batch_size(vram) + + if batch_ratio > batch_cap: + settings['gradient_accumulation_size'] = int(settings['batch_size'] / batch_cap) + messages.append(f"Batch ratio ({batch_ratio}) is expected to exceed your VRAM capacity ({'{:.3f}'.format(vram)}GB, suggested {batch_cap} batch size cap), adjusting gradient accumulation size to: {settings['gradient_accumulation_size']}") + + iterations = calc_iterations(epochs=settings['epochs'], lines=lines, batch_size=settings['batch_size']) + + if settings['epochs'] < settings['save_rate']: + settings['save_rate'] = settings['epochs'] + messages.append(f"Save rate is too small for the given iteration step, clamping save rate to: {settings['save_rate']}") + + if settings['epochs'] < settings['validation_rate']: + settings['validation_rate'] = settings['epochs'] + messages.append(f"Validation rate is too small for the given iteration step, clamping validation rate to: {settings['validation_rate']}") + + if settings['resume_state'] and not os.path.exists(settings['resume_state']): + settings['resume_state'] = None + messages.append("Resume path specified, but does not exist. Disabling...") + + if settings['bitsandbytes']: + messages.append("! EXPERIMENTAL ! BitsAndBytes requested.") + + if settings['half_p']: + if settings['bitsandbytes']: + settings['half_p'] = False + messages.append("Half Precision requested, but BitsAndBytes is also requested. Due to redundancies, disabling half precision...") + else: + messages.append("! EXPERIMENTAL ! Half Precision requested.") + if not os.path.exists(get_halfp_model_path()): + convert_to_halfp() + + steps = int(iterations / settings['epochs']) + + messages.append(f"For {settings['epochs']} epochs with {lines} lines in batches of {settings['batch_size']}, iterating for {iterations} steps ({steps}) steps per epoch)") + + return settings, messages + +def save_training_settings( **kwargs ): + messages = [] + settings = {} + settings.update(kwargs) + + + outjson = f'./training/{settings["voice"]}/train.json' + with open(outjson, 'w', encoding="utf-8") as f: + f.write(json.dumps(settings, indent='\t') ) + + settings['dataset_path'] = f"./training/{settings['voice']}/train.txt" + settings['validation_path'] = f"./training/{settings['voice']}/validation.txt" + + with open(settings['dataset_path'], 'r', encoding="utf-8") as f: + lines = len(f.readlines()) + + settings['iterations'] = calc_iterations(epochs=settings['epochs'], lines=lines, batch_size=settings['batch_size']) + + if not settings['source_model'] or settings['source_model'] == "auto": + settings['source_model'] = f"./models/tortoise/autoregressive{'_half' if settings['half_p'] else ''}.pth" + + if settings['half_p']: + if not os.path.exists(get_halfp_model_path()): + convert_to_halfp() + + messages.append(f"For {settings['epochs']} epochs with {lines} lines, iterating for {settings['iterations']} steps") + + iterations_per_epoch = settings['iterations'] / settings['epochs'] + + settings['save_rate'] = int(settings['save_rate'] * iterations_per_epoch) + settings['validation_rate'] = int(settings['validation_rate'] * iterations_per_epoch) + + iterations_per_epoch = int(iterations_per_epoch) + + if settings['save_rate'] < 1: + settings['save_rate'] = 1 + """ + if settings['validation_rate'] < 1: + settings['validation_rate'] = 1 + """ + """ + if settings['iterations'] % settings['save_rate'] != 0: + adjustment = int(settings['iterations'] / settings['save_rate']) * settings['save_rate'] + messages.append(f"Iteration rate is not evenly divisible by save rate, adjusting: {settings['iterations']} => {adjustment}") + settings['iterations'] = adjustment + """ + + settings['validation_batch_size'] = int(settings['batch_size'] / settings['gradient_accumulation_size']) + if not os.path.exists(settings['validation_path']): + settings['validation_enabled'] = False + messages.append("Validation not found, disabling validation...") + elif settings['validation_batch_size'] == 0: + settings['validation_enabled'] = False + messages.append("Validation batch size == 0, disabling validation...") + else: + with open(settings['validation_path'], 'r', encoding="utf-8") as f: + validation_lines = len(f.readlines()) + + if validation_lines < settings['validation_batch_size']: + settings['validation_batch_size'] = validation_lines + messages.append(f"Batch size exceeds validation dataset size, clamping validation batch size to {validation_lines}") + + settings['tokenizer_json'] = args.tokenizer_json if args.tokenizer_json else get_tokenizer_jsons()[0] + + if settings['gpus'] > get_device_count(): + settings['gpus'] = get_device_count() + + # what an utter mistake this was + settings['optimizer'] = 'adamw' # if settings['gpus'] == 1 else 'adamw_zero' + + if 'learning_rate_scheme' not in settings or settings['learning_rate_scheme'] not in LEARNING_RATE_SCHEMES: + settings['learning_rate_scheme'] = "Multistep" + + settings['learning_rate_scheme'] = LEARNING_RATE_SCHEMES[settings['learning_rate_scheme']] + + learning_rate_schema = [f"default_lr_scheme: {settings['learning_rate_scheme']}"] + if settings['learning_rate_scheme'] == "MultiStepLR": + if not settings['learning_rate_schedule']: + settings['learning_rate_schedule'] = LEARNING_RATE_SCHEDULE + elif isinstance(settings['learning_rate_schedule'],str): + settings['learning_rate_schedule'] = json.loads(settings['learning_rate_schedule']) + + settings['learning_rate_schedule'] = schedule_learning_rate( iterations_per_epoch, settings['learning_rate_schedule'] ) + + learning_rate_schema.append(f" gen_lr_steps: {settings['learning_rate_schedule']}") + learning_rate_schema.append(f" lr_gamma: 0.5") + elif settings['learning_rate_scheme'] == "CosineAnnealingLR_Restart": + epochs = settings['epochs'] + restarts = settings['learning_rate_restarts'] + restart_period = int(epochs / restarts) + + if 'learning_rate_warmup' not in settings: + settings['learning_rate_warmup'] = 0 + if 'learning_rate_min' not in settings: + settings['learning_rate_min'] = 1e-08 + + if 'learning_rate_period' not in settings: + settings['learning_rate_period'] = [ iterations_per_epoch * restart_period for x in range(epochs) ] + + settings['learning_rate_restarts'] = [ iterations_per_epoch * (x+1) * restart_period for x in range(restarts) ] # [52, 104, 156, 208] + + if 'learning_rate_restart_weights' not in settings: + settings['learning_rate_restart_weights'] = [ ( restarts - x - 1 ) / restarts for x in range(restarts) ] # [.75, .5, .25, .125] + settings['learning_rate_restart_weights'][-1] = settings['learning_rate_restart_weights'][-2] * 0.5 + + learning_rate_schema.append(f" T_period: {settings['learning_rate_period']}") + learning_rate_schema.append(f" warmup: {settings['learning_rate_warmup']}") + learning_rate_schema.append(f" eta_min: !!float {settings['learning_rate_min']}") + learning_rate_schema.append(f" restarts: {settings['learning_rate_restarts']}") + learning_rate_schema.append(f" restart_weights: {settings['learning_rate_restart_weights']}") + settings['learning_rate_scheme'] = "\n".join(learning_rate_schema) + + if settings['resume_state']: + settings['source_model'] = f"# pretrain_model_gpt: '{settings['source_model']}'" + settings['resume_state'] = f"resume_state: '{settings['resume_state']}'" + else: + settings['source_model'] = f"pretrain_model_gpt: '{settings['source_model']}'" + settings['resume_state'] = f"# resume_state: '{settings['resume_state']}'" + + def use_template(template, out): + with open(template, 'r', encoding="utf-8") as f: + yaml = f.read() + + # i could just load and edit the YAML directly, but this is easier, as I don't need to bother with path traversals + for k in settings: + if settings[k] is None: + continue + yaml = yaml.replace(f"${{{k}}}", str(settings[k])) + + with open(out, 'w', encoding="utf-8") as f: + f.write(yaml) + + if args.tts_backend == "tortoise": + use_template(f'./models/.template.dlas.yaml', f'./training/{settings["voice"]}/train.yaml') + elif args.tts_backend == "vall-e": + settings['model_name'] = "[ 'ar-quarter', 'nar-quarter' ]" + use_template(f'./models/.template.valle.yaml', f'./training/{settings["voice"]}/config.yaml') + + messages.append(f"Saved training output") + return settings, messages + +def import_voices(files, saveAs=None, progress=None): + global args + + if not isinstance(files, list): + files = [files] + + for file in tqdm(files, desc="Importing voice files"): + j, latents = read_generate_settings(file, read_latents=True) + + if j is not None and saveAs is None: + saveAs = j['voice'] + if saveAs is None or saveAs == "": + raise Exception("Specify a voice name") + + outdir = f'{get_voice_dir()}/{saveAs}/' + os.makedirs(outdir, exist_ok=True) + + if latents: + print(f"Importing latents to {latents}") + with open(f'{outdir}/cond_latents.pth', 'wb') as f: + f.write(latents) + latents = f'{outdir}/cond_latents.pth' + print(f"Imported latents to {latents}") + else: + filename = file.name + if filename[-4:] != ".wav": + raise Exception("Please convert to a WAV first") + + path = f"{outdir}/{os.path.basename(filename)}" + print(f"Importing voice to {path}") + + waveform, sample_rate = torchaudio.load(filename) + + if args.voice_fixer: + if not voicefixer: + load_voicefixer() + + waveform, sample_rate = resample(waveform, sample_rate, 44100) + torchaudio.save(path, waveform, sample_rate) + + print(f"Running 'voicefixer' on voice sample: {path}") + voicefixer.restore( + input = path, + output = path, + cuda=get_device_name() == "cuda" and args.voice_fixer_use_cuda, + #mode=mode, + ) + else: + torchaudio.save(path, waveform, sample_rate) + + print(f"Imported voice to {path}") + +def relative_paths( dirs ): + return [ './' + os.path.relpath( d ).replace("\\", "/") for d in dirs ] + +def get_voice( name, dir=get_voice_dir(), load_latents=True, extensions=["wav", "mp3", "flac"] ): + subj = f'{dir}/{name}/' + if not os.path.isdir(subj): + return + files = os.listdir(subj) + + if load_latents: + extensions.append("pth") + + voice = [] + for file in files: + ext = os.path.splitext(file)[-1][1:] + if ext not in extensions: + continue + + voice.append(f'{subj}/{file}') + + return sorted( voice ) + +def get_voice_list(dir=get_voice_dir(), append_defaults=False, extensions=["wav", "mp3", "flac", "pth"]): + defaults = [ "random", "microphone" ] + os.makedirs(dir, exist_ok=True) + #res = sorted([d for d in os.listdir(dir) if d not in defaults and os.path.isdir(os.path.join(dir, d)) and len(os.listdir(os.path.join(dir, d))) > 0 ]) + + res = [] + for name in os.listdir(dir): + if name in defaults: + continue + if not os.path.isdir(f'{dir}/{name}'): + continue + if len(os.listdir(os.path.join(dir, name))) == 0: + continue + files = get_voice( name, dir=dir, extensions=extensions ) + + if len(files) > 0: + res.append(name) + else: + for subdir in os.listdir(f'{dir}/{name}'): + if not os.path.isdir(f'{dir}/{name}/{subdir}'): + continue + files = get_voice( f'{name}/{subdir}', dir=dir, extensions=extensions ) + if len(files) == 0: + continue + res.append(f'{name}/{subdir}') + + res = sorted(res) + + if append_defaults: + res = res + defaults + + return res + +def get_valle_models(dir="./training/"): + return [ f'{dir}/{d}/config.yaml' for d in os.listdir(dir) if os.path.exists(f'{dir}/{d}/config.yaml') ] + +def get_autoregressive_models(dir="./models/finetunes/", prefixed=False, auto=False): + os.makedirs(dir, exist_ok=True) + base = [get_model_path('autoregressive.pth')] + halfp = get_halfp_model_path() + if os.path.exists(halfp): + base.append(halfp) + + additionals = sorted([f'{dir}/{d}' for d in os.listdir(dir) if d[-4:] == ".pth" ]) + found = [] + for training in os.listdir(f'./training/'): + if not os.path.isdir(f'./training/{training}/') or not os.path.isdir(f'./training/{training}/finetune/') or not os.path.isdir(f'./training/{training}/finetune/models/'): + continue + models = sorted([ int(d[:-8]) for d in os.listdir(f'./training/{training}/finetune/models/') if d[-8:] == "_gpt.pth" ]) + found = found + [ f'./training/{training}/finetune/models/{d}_gpt.pth' for d in models ] + + res = base + additionals + found + + if prefixed: + for i in range(len(res)): + path = res[i] + hash = hash_file(path) + shorthash = hash[:8] + + res[i] = f'[{shorthash}] {path}' + + paths = relative_paths(res) + if auto: + paths = ["auto"] + paths + + return paths + +def get_diffusion_models(dir="./models/finetunes/", prefixed=False): + return relative_paths([ get_model_path('diffusion_decoder.pth') ]) + +def get_tokenizer_jsons( dir="./models/tokenizers/" ): + additionals = sorted([ f'{dir}/{d}' for d in os.listdir(dir) if d[-5:] == ".json" ]) if os.path.isdir(dir) else [] + return relative_paths([ "./modules/tortoise-tts/tortoise/data/tokenizer.json" ] + additionals) + +def tokenize_text( text, config=None, stringed=True, skip_specials=False ): + from tortoise.utils.tokenizer import VoiceBpeTokenizer + + if not config: + config = args.tokenizer_json if args.tokenizer_json else get_tokenizer_jsons()[0] + + if not tts: + tokenizer = VoiceBpeTokenizer(config) + else: + tokenizer = tts.tokenizer + + encoded = tokenizer.encode(text) + decoded = tokenizer.tokenizer.decode(encoded, skip_special_tokens=skip_specials).split(" ") + + if stringed: + return "\n".join([ str(encoded), str(decoded) ]) + + return decoded + +def get_dataset_list(dir="./training/"): + return sorted([d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d)) and "train.txt" in os.listdir(os.path.join(dir, d)) ]) + +def get_training_list(dir="./training/"): + if args.tts_backend == "tortoise": + return sorted([f'./training/{d}/train.yaml' for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d)) and "train.yaml" in os.listdir(os.path.join(dir, d)) ]) + else: + return sorted([f'./training/{d}/config.yaml' for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d)) and "config.yaml" in os.listdir(os.path.join(dir, d)) ]) + +def pad(num, zeroes): + return str(num).zfill(zeroes+1) + +def curl(url): + try: + req = urllib.request.Request(url, headers={'User-Agent': 'Python'}) + conn = urllib.request.urlopen(req) + data = conn.read() + data = data.decode() + data = json.loads(data) + conn.close() + return data + except Exception as e: + print(e) + return None + +def check_for_updates( dir = None ): + if dir is None: + check_for_updates("./.git/") + check_for_updates("./.git/modules/dlas/") + check_for_updates("./.git/modules/tortoise-tts/") + return + + git_dir = dir + if not os.path.isfile(f'{git_dir}/FETCH_HEAD'): + print(f"Cannot check for updates for {dir}: not from a git repo") + return False + + with open(f'{git_dir}/FETCH_HEAD', 'r', encoding="utf-8") as f: + head = f.read() + + match = re.findall(r"^([a-f0-9]+).+?https:\/\/(.+?)\/(.+?)\/(.+?)\n", head) + if match is None or len(match) == 0: + print(f"Cannot check for updates for {dir}: cannot parse FETCH_HEAD") + return False + + match = match[0] + + local = match[0] + host = match[1] + owner = match[2] + repo = match[3] + + res = curl(f"https://{host}/api/v1/repos/{owner}/{repo}/branches/") #this only works for gitea instances + + if res is None or len(res) == 0: + print(f"Cannot check for updates for {dir}: cannot fetch from remote") + return False + + remote = res[0]["commit"]["id"] + + if remote != local: + print(f"New version found for {dir}: {local[:8]} => {remote[:8]}") + return True + + return False + +def notify_progress(message, progress=None, verbose=True): + if verbose: + print(message) + + if progress is None: + tqdm.write(message) + else: + progress(0, desc=message) + +def get_args(): + global args + return args + +def setup_args(cli=False): + global args + + default_arguments = { + 'share': False, + 'listen': None, + 'check-for-updates': False, + 'models-from-local-only': False, + 'low-vram': False, + 'sample-batch-size': None, + 'unsqueeze-sample-batches': False, + 'embed-output-metadata': True, + 'latents-lean-and-mean': True, + 'voice-fixer': False, # getting tired of long initialization times in a Colab for downloading a large dataset for it + 'use-deepspeed': False, + 'use-hifigan': False, + 'voice-fixer-use-cuda': True, + + + 'force-cpu-for-conditioning-latents': False, + 'defer-tts-load': False, + 'device-override': None, + 'prune-nonfinal-outputs': True, + 'concurrency-count': 2, + 'autocalculate-voice-chunk-duration-size': 10, + + 'output-sample-rate': 44100, + 'output-volume': 1, + 'results-folder': "./results/", + + 'hf-token': None, + 'tts-backend': TTSES[0], + + 'autoregressive-model': None, + 'diffusion-model': None, + 'vocoder-model': VOCODERS[-1], + 'tokenizer-json': None, + + 'phonemizer-backend': 'espeak', + + 'valle-model': None, + + 'whisper-backend': 'openai/whisper', + 'whisper-model': "base", + 'whisper-batchsize': 1, + + 'training-default-halfp': False, + 'training-default-bnb': True, + + 'websocket-listen-address': "127.0.0.1", + 'websocket-listen-port': 8069, + 'websocket-enabled': False + } + + if os.path.isfile('./config/exec.json'): + with open(f'./config/exec.json', 'r', encoding="utf-8") as f: + try: + overrides = json.load(f) + for k in overrides: + default_arguments[k] = overrides[k] + except Exception as e: + print(e) + pass + + parser = argparse.ArgumentParser(allow_abbrev=not cli) + parser.add_argument("--share", action='store_true', default=default_arguments['share'], help="Lets Gradio return a public URL to use anywhere") + parser.add_argument("--listen", default=default_arguments['listen'], help="Path for Gradio to listen on") + parser.add_argument("--check-for-updates", action='store_true', default=default_arguments['check-for-updates'], help="Checks for update on startup") + parser.add_argument("--models-from-local-only", action='store_true', default=default_arguments['models-from-local-only'], help="Only loads models from disk, does not check for updates for models") + parser.add_argument("--low-vram", action='store_true', default=default_arguments['low-vram'], help="Disables some optimizations that increases VRAM usage") + parser.add_argument("--no-embed-output-metadata", action='store_false', default=not default_arguments['embed-output-metadata'], help="Disables embedding output metadata into resulting WAV files for easily fetching its settings used with the web UI (data is stored in the lyrics metadata tag)") + parser.add_argument("--latents-lean-and-mean", action='store_true', default=default_arguments['latents-lean-and-mean'], help="Exports the bare essentials for latents.") + parser.add_argument("--voice-fixer", action='store_true', default=default_arguments['voice-fixer'], help="Uses python module 'voicefixer' to improve audio quality, if available.") + parser.add_argument("--voice-fixer-use-cuda", action='store_true', default=default_arguments['voice-fixer-use-cuda'], help="Hints to voicefixer to use CUDA, if available.") + parser.add_argument("--use-deepspeed", action='store_true', default=default_arguments['use-deepspeed'], help="Use deepspeed for speed bump.") + parser.add_argument("--use-hifigan", action='store_true', default=default_arguments['use-hifigan'], help="Use Hifigan instead of Diffusion") + + parser.add_argument("--force-cpu-for-conditioning-latents", default=default_arguments['force-cpu-for-conditioning-latents'], action='store_true', help="Forces computing conditional latents to be done on the CPU (if you constantyl OOM on low chunk counts)") + parser.add_argument("--defer-tts-load", default=default_arguments['defer-tts-load'], action='store_true', help="Defers loading TTS model") + parser.add_argument("--prune-nonfinal-outputs", default=default_arguments['prune-nonfinal-outputs'], action='store_true', help="Deletes non-final output files on completing a generation") + parser.add_argument("--device-override", default=default_arguments['device-override'], help="A device string to override pass through Torch") + parser.add_argument("--sample-batch-size", default=default_arguments['sample-batch-size'], type=int, help="Sets how many batches to use during the autoregressive samples pass") + parser.add_argument("--unsqueeze-sample-batches", default=default_arguments['unsqueeze-sample-batches'], action='store_true', help="Unsqueezes sample batches to process one by one after sampling") + parser.add_argument("--concurrency-count", type=int, default=default_arguments['concurrency-count'], help="How many Gradio events to process at once") + parser.add_argument("--autocalculate-voice-chunk-duration-size", type=float, default=default_arguments['autocalculate-voice-chunk-duration-size'], help="Number of seconds to suggest voice chunk size for (for example, 100 seconds of audio at 10 seconds per chunk will suggest 10 chunks)") + parser.add_argument("--output-sample-rate", type=int, default=default_arguments['output-sample-rate'], help="Sample rate to resample the output to (from 24KHz)") + parser.add_argument("--output-volume", type=float, default=default_arguments['output-volume'], help="Adjusts volume of output") + parser.add_argument("--results-folder", type=str, default=default_arguments['results-folder'], help="Sets output directory") + + parser.add_argument("--hf-token", type=str, default=default_arguments['hf-token'], help="HuggingFace Token") + parser.add_argument("--tts-backend", default=default_arguments['tts-backend'], help="Specifies which TTS backend to use.") + + parser.add_argument("--autoregressive-model", default=default_arguments['autoregressive-model'], help="Specifies which autoregressive model to use for sampling.") + parser.add_argument("--diffusion-model", default=default_arguments['diffusion-model'], help="Specifies which diffusion model to use for sampling.") + parser.add_argument("--vocoder-model", default=default_arguments['vocoder-model'], action='store_true', help="Specifies with vocoder to use") + parser.add_argument("--tokenizer-json", default=default_arguments['tokenizer-json'], help="Specifies which tokenizer json to use for tokenizing.") + + parser.add_argument("--phonemizer-backend", default=default_arguments['phonemizer-backend'], help="Specifies which phonemizer backend to use.") + + parser.add_argument("--valle-model", default=default_arguments['valle-model'], help="Specifies which VALL-E model to use for sampling.") + + parser.add_argument("--whisper-backend", default=default_arguments['whisper-backend'], action='store_true', help="Picks which whisper backend to use (openai/whisper, lightmare/whispercpp)") + parser.add_argument("--whisper-model", default=default_arguments['whisper-model'], help="Specifies which whisper model to use for transcription.") + parser.add_argument("--whisper-batchsize", type=int, default=default_arguments['whisper-batchsize'], help="Specifies batch size for WhisperX") + + parser.add_argument("--training-default-halfp", action='store_true', default=default_arguments['training-default-halfp'], help="Training default: halfp") + parser.add_argument("--training-default-bnb", action='store_true', default=default_arguments['training-default-bnb'], help="Training default: bnb") + + parser.add_argument("--websocket-listen-port", type=int, default=default_arguments['websocket-listen-port'], help="Websocket server listen port, default: 8069") + parser.add_argument("--websocket-listen-address", default=default_arguments['websocket-listen-address'], help="Websocket server listen address, default: 127.0.0.1") + parser.add_argument("--websocket-enabled", action='store_true', default=default_arguments['websocket-enabled'], help="Websocket API server enabled, default: false") + + if cli: + args, unknown = parser.parse_known_args() + else: + args = parser.parse_args() + + args.embed_output_metadata = not args.no_embed_output_metadata + + if not args.device_override: + set_device_name(args.device_override) + + if args.sample_batch_size == 0 and get_device_batch_size() == 1: + print("!WARNING! Automatically deduced sample batch size returned 1.") + + args.listen_host = None + args.listen_port = None + args.listen_path = None + if args.listen: + try: + match = re.findall(r"^(?:(.+?):(\d+))?(\/.*?)?$", args.listen)[0] + + args.listen_host = match[0] if match[0] != "" else "127.0.0.1" + args.listen_port = match[1] if match[1] != "" else None + args.listen_path = match[2] if match[2] != "" else "/" + except Exception as e: + pass + + if args.listen_port is not None: + args.listen_port = int(args.listen_port) + if args.listen_port == 0: + args.listen_port = None + + return args + +def get_default_settings( hypenated=True ): + settings = { + 'listen': None if not args.listen else args.listen, + 'share': args.share, + 'low-vram':args.low_vram, + 'check-for-updates':args.check_for_updates, + 'models-from-local-only':args.models_from_local_only, + 'force-cpu-for-conditioning-latents': args.force_cpu_for_conditioning_latents, + 'defer-tts-load': args.defer_tts_load, + 'prune-nonfinal-outputs': args.prune_nonfinal_outputs, + 'device-override': args.device_override, + 'sample-batch-size': args.sample_batch_size, + 'unsqueeze-sample-batches': args.unsqueeze_sample_batches, + 'embed-output-metadata': args.embed_output_metadata, + 'latents-lean-and-mean': args.latents_lean_and_mean, + 'voice-fixer': args.voice_fixer, + 'use-deepspeed': args.use_deepspeed, + 'use-hifigan': args.use_hifigan, + 'voice-fixer-use-cuda': args.voice_fixer_use_cuda, + 'concurrency-count': args.concurrency_count, + 'output-sample-rate': args.output_sample_rate, + 'autocalculate-voice-chunk-duration-size': args.autocalculate_voice_chunk_duration_size, + 'output-volume': args.output_volume, + 'results-folder': args.results_folder, + + 'hf-token': args.hf_token, + 'tts-backend': args.tts_backend, + + 'autoregressive-model': args.autoregressive_model, + 'diffusion-model': args.diffusion_model, + 'vocoder-model': args.vocoder_model, + 'tokenizer-json': args.tokenizer_json, + + 'phonemizer-backend': args.phonemizer_backend, + + 'valle-model': args.valle_model, + + 'whisper-backend': args.whisper_backend, + 'whisper-model': args.whisper_model, + 'whisper-batchsize': args.whisper_batchsize, + + 'training-default-halfp': args.training_default_halfp, + 'training-default-bnb': args.training_default_bnb, + } + + res = {} + for k in settings: + res[k.replace("-", "_") if not hypenated else k] = settings[k] + return res + +def update_args( **kwargs ): + global args + + settings = get_default_settings(hypenated=False) + settings.update(kwargs) + + args.listen = settings['listen'] + args.share = settings['share'] + args.check_for_updates = settings['check_for_updates'] + args.models_from_local_only = settings['models_from_local_only'] + args.low_vram = settings['low_vram'] + args.force_cpu_for_conditioning_latents = settings['force_cpu_for_conditioning_latents'] + args.defer_tts_load = settings['defer_tts_load'] + args.prune_nonfinal_outputs = settings['prune_nonfinal_outputs'] + args.device_override = settings['device_override'] + args.sample_batch_size = settings['sample_batch_size'] + args.unsqueeze_sample_batches = settings['unsqueeze_sample_batches'] + args.embed_output_metadata = settings['embed_output_metadata'] + args.latents_lean_and_mean = settings['latents_lean_and_mean'] + args.voice_fixer = settings['voice_fixer'] + args.voice_fixer_use_cuda = settings['voice_fixer_use_cuda'] + args.use_deepspeed = settings['use_deepspeed'] + args.use_hifigan = settings['use_hifigan'] + args.concurrency_count = settings['concurrency_count'] + args.output_sample_rate = 44000 + args.autocalculate_voice_chunk_duration_size = settings['autocalculate_voice_chunk_duration_size'] + args.output_volume = settings['output_volume'] + args.results_folder = settings['results_folder'] + + args.hf_token = settings['hf_token'] + args.tts_backend = settings['tts_backend'] + + args.autoregressive_model = settings['autoregressive_model'] + args.diffusion_model = settings['diffusion_model'] + args.vocoder_model = settings['vocoder_model'] + args.tokenizer_json = settings['tokenizer_json'] + + args.phonemizer_backend = settings['phonemizer_backend'] + + args.valle_model = settings['valle_model'] + + args.whisper_backend = settings['whisper_backend'] + args.whisper_model = settings['whisper_model'] + args.whisper_batchsize = settings['whisper_batchsize'] + + args.training_default_halfp = settings['training_default_halfp'] + args.training_default_bnb = settings['training_default_bnb'] + + save_args_settings() + +def save_args_settings(): + global args + settings = get_default_settings() + + os.makedirs('./config/', exist_ok=True) + with open(f'./config/exec.json', 'w', encoding="utf-8") as f: + f.write(json.dumps(settings, indent='\t') ) + +# super kludgy )`; +def import_generate_settings(file = None): + if not file: + file = "./config/generate.json" + + res = { + 'text': None, + 'delimiter': None, + 'emotion': None, + 'prompt': None, + 'voice': "random", + 'mic_audio': None, + 'voice_latents_chunks': None, + 'candidates': None, + 'seed': None, + 'num_autoregressive_samples': 16, + 'diffusion_iterations': 30, + 'temperature': 0.8, + 'diffusion_sampler': "DDIM", + 'breathing_room': 8 , + 'cvvp_weight': 0.0, + 'top_p': 0.8, + 'diffusion_temperature': 1.0, + 'length_penalty': 1.0, + 'repetition_penalty': 2.0, + 'cond_free_k': 2.0, + 'experimentals': None, + } + + settings, _ = read_generate_settings(file, read_latents=False) + + if settings is not None: + res.update(settings) + + return res + +def reset_generate_settings(): + with open(f'./config/generate.json', 'w', encoding="utf-8") as f: + f.write(json.dumps({}, indent='\t') ) + return import_generate_settings() + +def read_generate_settings(file, read_latents=True): + j = None + latents = None + + if isinstance(file, list) and len(file) == 1: + file = file[0] + + try: + if file is not None: + if hasattr(file, 'name'): + file = file.name + + if file[-4:] == ".wav": + metadata = music_tag.load_file(file) + if 'lyrics' in metadata: + j = json.loads(str(metadata['lyrics'])) + elif file[-5:] == ".json": + with open(file, 'r') as f: + j = json.load(f) + except Exception as e: + pass + + if j is not None: + if 'latents' in j: + if read_latents: + latents = base64.b64decode(j['latents']) + del j['latents'] + + + if "time" in j: + j["time"] = "{:.3f}".format(j["time"]) + + + + return ( + j, + latents, + ) + +def version_check_tts( min_version ): + global tts + if not tts: + raise Exception("TTS is not initialized") + + if not hasattr(tts, 'version'): + return False + + if min_version[0] > tts.version[0]: + return True + if min_version[1] > tts.version[1]: + return True + if min_version[2] >= tts.version[2]: + return True + return False + +def load_tts( restart=False, + # TorToiSe configs + autoregressive_model=None, diffusion_model=None, vocoder_model=None, tokenizer_json=None, + # VALL-E configs + valle_model=None, +): + global args + global tts + + if restart: + unload_tts() + + tts_loading = True + if args.tts_backend == "tortoise": + if autoregressive_model: + args.autoregressive_model = autoregressive_model + else: + autoregressive_model = args.autoregressive_model + + if autoregressive_model == "auto": + autoregressive_model = deduce_autoregressive_model() + + if diffusion_model: + args.diffusion_model = diffusion_model + else: + diffusion_model = args.diffusion_model + + if vocoder_model: + args.vocoder_model = vocoder_model + else: + vocoder_model = args.vocoder_model + + if tokenizer_json: + args.tokenizer_json = tokenizer_json + else: + tokenizer_json = args.tokenizer_json + + if get_device_name() == "cpu": + print("!!!! WARNING !!!! No GPU available in PyTorch. You may need to reinstall PyTorch.") + + + if args.use_hifigan: + print("Loading Tortoise with Hifigan") + tts = Toroise_TTS_Hifi(autoregressive_model_path=autoregressive_model, + tokenizer_json=tokenizer_json, + use_deepspeed=args.use_deepspeed) + else: + print(f"Loading TorToiSe... (AR: {autoregressive_model}, diffusion: {diffusion_model}, vocoder: {vocoder_model})") + tts = TorToise_TTS(minor_optimizations=not args.low_vram, + autoregressive_model_path=autoregressive_model, + diffusion_model_path=diffusion_model, + vocoder_model=vocoder_model, + tokenizer_json=tokenizer_json, + unsqueeze_sample_batches=args.unsqueeze_sample_batches, + use_deepspeed=args.use_deepspeed) + + elif args.tts_backend == "vall-e": + if valle_model: + args.valle_model = valle_model + else: + valle_model = args.valle_model + + print(f"Loading VALL-E... (Config: {valle_model})") + tts = VALLE_TTS(config=args.valle_model) + elif args.tts_backend == "bark": + + print(f"Loading Bark...") + tts = Bark_TTS(small=args.low_vram) + + print("Loaded TTS, ready for generation.") + tts_loading = False + return tts + +def unload_tts(): + global tts + + if tts: + del tts + tts = None + print("Unloaded TTS") + do_gc() + +def reload_tts(): + unload_tts() + load_tts() + +def get_current_voice(): + global current_voice + if current_voice: + return current_voice + + settings, _ = read_generate_settings("./config/generate.json", read_latents=False) + + if settings and "voice" in settings['voice']: + return settings["voice"] + + return None + +def deduce_autoregressive_model(voice=None): + if not voice: + voice = get_current_voice() + + if voice: + if os.path.exists(f'./models/finetunes/{voice}.pth'): + return f'./models/finetunes/{voice}.pth' + + dir = f'./training/{voice}/finetune/models/' + if os.path.isdir(dir): + counts = sorted([ int(d[:-8]) for d in os.listdir(dir) if d[-8:] == "_gpt.pth" ]) + names = [ f'{dir}/{d}_gpt.pth' for d in counts ] + if len(names) > 0: + return names[-1] + + if args.autoregressive_model != "auto": + return args.autoregressive_model + + return get_model_path('autoregressive.pth') + +def update_autoregressive_model(autoregressive_model_path): + if args.tts_backend != "tortoise": + raise f"Unsupported backend: {args.tts_backend}" + + if autoregressive_model_path == "auto": + autoregressive_model_path = deduce_autoregressive_model() + else: + match = re.findall(r'^\[[a-fA-F0-9]{8}\] (.+?)$', autoregressive_model_path) + if match: + autoregressive_model_path = match[0] + + if not autoregressive_model_path or not os.path.exists(autoregressive_model_path): + print(f"Invalid model: {autoregressive_model_path}") + return + + args.autoregressive_model = autoregressive_model_path + save_args_settings() + print(f'Stored autoregressive model to settings: {autoregressive_model_path}') + + global tts + if not tts: + if tts_loading: + raise Exception("TTS is still initializing...") + return + + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + + if autoregressive_model_path == tts.autoregressive_model_path: + return + + tts.load_autoregressive_model(autoregressive_model_path) + + do_gc() + + return autoregressive_model_path + +def update_diffusion_model(diffusion_model_path): + if args.tts_backend != "tortoise": + raise f"Unsupported backend: {args.tts_backend}" + + match = re.findall(r'^\[[a-fA-F0-9]{8}\] (.+?)$', diffusion_model_path) + if match: + diffusion_model_path = match[0] + + if not diffusion_model_path or not os.path.exists(diffusion_model_path): + print(f"Invalid model: {diffusion_model_path}") + return + + args.diffusion_model = diffusion_model_path + save_args_settings() + print(f'Stored diffusion model to settings: {diffusion_model_path}') + + global tts + if not tts: + if tts_loading: + raise Exception("TTS is still initializing...") + return + + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + if diffusion_model_path == "auto": + diffusion_model_path = deduce_diffusion_model() + + if diffusion_model_path == tts.diffusion_model_path: + return + + tts.load_diffusion_model(diffusion_model_path) + + do_gc() + + return diffusion_model_path + +def update_vocoder_model(vocoder_model): + if args.tts_backend != "tortoise": + raise f"Unsupported backend: {args.tts_backend}" + + args.vocoder_model = vocoder_model + save_args_settings() + print(f'Stored vocoder model to settings: {vocoder_model}') + + global tts + if not tts: + if tts_loading: + raise Exception("TTS is still initializing...") + return + + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + print(f"Loading model: {vocoder_model}") + tts.load_vocoder_model(vocoder_model) + print(f"Loaded model: {tts.vocoder_model}") + + do_gc() + + return vocoder_model + +def update_tokenizer(tokenizer_json): + if args.tts_backend != "tortoise": + raise f"Unsupported backend: {args.tts_backend}" + + args.tokenizer_json = tokenizer_json + save_args_settings() + print(f'Stored tokenizer to settings: {tokenizer_json}') + + global tts + if not tts: + if tts_loading: + raise Exception("TTS is still initializing...") + return + + if hasattr(tts, "loading") and tts.loading: + raise Exception("TTS is still initializing...") + + print(f"Loading tokenizer vocab: {tokenizer_json}") + tts.load_tokenizer_json(tokenizer_json) + print(f"Loaded tokenizer vocab: {tts.tokenizer_json}") + + do_gc() + + return vocoder_model + +def load_voicefixer(restart=False): + global voicefixer + + if restart: + unload_voicefixer() + + try: + print("Loading Voicefixer") + from voicefixer import VoiceFixer + voicefixer = VoiceFixer() + print("Loaded Voicefixer") + except Exception as e: + print(f"Error occurred while tring to initialize voicefixer: {e}") + if voicefixer: + del voicefixer + voicefixer = None + +def unload_voicefixer(): + global voicefixer + + if voicefixer: + del voicefixer + voicefixer = None + print("Unloaded Voicefixer") + + do_gc() + +def load_whisper_model(language=None, model_name=None, progress=None): + global whisper_model + global whisper_align_model + + if args.whisper_backend not in WHISPER_BACKENDS: + raise Exception(f"unavailable backend: {args.whisper_backend}") + + if not model_name: + model_name = args.whisper_model + else: + args.whisper_model = model_name + save_args_settings() + + if language and f'{model_name}.{language}' in WHISPER_SPECIALIZED_MODELS: + model_name = f'{model_name}.{language}' + print(f"Loading specialized model for language: {language}") + + notify_progress(f"Loading Whisper model: {model_name}", progress=progress) + + if args.whisper_backend == "openai/whisper": + import whisper + try: + #is it possible for model to fit on vram but go oom later on while executing on data? + whisper_model = whisper.load_model(model_name) + except: + print("Out of VRAM memory. falling back to loading Whisper on CPU.") + whisper_model = whisper.load_model(model_name, device="cpu") + elif args.whisper_backend == "lightmare/whispercpp": + from whispercpp import Whisper + if not language: + language = 'auto' + + b_lang = language.encode('ascii') + whisper_model = Whisper(model_name, models_dir='./models/', language=b_lang) + elif args.whisper_backend == "m-bain/whisperx": + import whisper, whisperx + device = "cuda" if get_device_name() == "cuda" else "cpu" + whisper_model = whisperx.load_model(model_name, device) + whisper_align_model = whisperx.load_align_model(model_name="WAV2VEC2_ASR_LARGE_LV60K_960H" if language=="en" else None, language_code=language, device=device) + + print("Loaded Whisper model") + +def unload_whisper(): + global whisper_model + global whisper_align_model + + if whisper_align_model: + del whisper_align_model + whisper_align_model = None + + if whisper_model: + del whisper_model + whisper_model = None + print("Unloaded Whisper") + + do_gc() + +# shamelessly borrowed from Voldy's Web UI: https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/modules/extras.py#L74 +def merge_models( primary_model_name, secondary_model_name, alpha, progress=gr.Progress() ): + key_blacklist = [] + + def weighted_sum(theta0, theta1, alpha): + return ((1 - alpha) * theta0) + (alpha * theta1) + + def read_model( filename ): + print(f"Loading {filename}") + return torch.load(filename) + + theta_func = weighted_sum + + theta_0 = read_model(primary_model_name) + theta_1 = read_model(secondary_model_name) + + for key in tqdm(theta_0.keys(), desc="Merging..."): + if key in key_blacklist: + print("Skipping ignored key:", key) + continue + + a = theta_0[key] + b = theta_1[key] + + if a.dtype != torch.float32 and a.dtype != torch.float16: + print("Skipping key:", key, a.dtype) + continue + + if b.dtype != torch.float32 and b.dtype != torch.float16: + print("Skipping key:", key, b.dtype) + continue + + theta_0[key] = theta_func(a, b, alpha) + + del theta_1 + + primary_basename = os.path.splitext(os.path.basename(primary_model_name))[0] + secondary_basename = os.path.splitext(os.path.basename(secondary_model_name))[0] + suffix = "{:.3f}".format(alpha) + output_path = f'./models/finetunes/{primary_basename}_{secondary_basename}_{suffix}_merge.pth' + + torch.save(theta_0, output_path) + message = f"Saved to {output_path}" + print(message) + return message diff --git a/src/webui.py b/src/webui.py new file mode 100644 index 0000000..68b4ccf --- /dev/null +++ b/src/webui.py @@ -0,0 +1,979 @@ +import os +import argparse +import time +import json +import base64 +import re +import inspect +import urllib.request + +import torch +import torchaudio +import music_tag +import gradio as gr +import gradio.utils + +from datetime import datetime + +import tortoise.api +from tortoise.utils.audio import get_voice_dir, get_voices +from tortoise.utils.device import get_device_count + +from utils import * + +args = setup_args() + +GENERATE_SETTINGS = {} +TRANSCRIBE_SETTINGS = {} +EXEC_SETTINGS = {} +TRAINING_SETTINGS = {} +MERGER_SETTINGS = {} +GENERATE_SETTINGS_ARGS = [] + +PRESETS = { + 'Ultra Fast': {'num_autoregressive_samples': 16, 'diffusion_iterations': 30, 'cond_free': False}, + 'Fast': {'num_autoregressive_samples': 96, 'diffusion_iterations': 80}, + 'Standard': {'num_autoregressive_samples': 256, 'diffusion_iterations': 200}, + 'High Quality': {'num_autoregressive_samples': 256, 'diffusion_iterations': 400}, +} + +HISTORY_HEADERS = { + "Name": "", + "Samples": "num_autoregressive_samples", + "Iterations": "diffusion_iterations", + "Temp.": "temperature", + "Sampler": "diffusion_sampler", + "CVVP": "cvvp_weight", + "Top P": "top_p", + "Diff. Temp.": "diffusion_temperature", + "Len Pen": "length_penalty", + "Rep Pen": "repetition_penalty", + "Cond-Free K": "cond_free_k", + "Time": "time", + "Datetime": "datetime", + "Model": "model", + "Model Hash": "model_hash", +} + +# can't use *args OR **kwargs if I want to retain the ability to use progress +def generate_proxy( + text, + delimiter, + emotion, + prompt, + voice, + mic_audio, + voice_latents_chunks, + candidates, + seed, + num_autoregressive_samples, + diffusion_iterations, + temperature, + diffusion_sampler, + breathing_room, + cvvp_weight, + top_p, + diffusion_temperature, + length_penalty, + repetition_penalty, + cond_free_k, + experimentals, + voice_latents_original_ar, + voice_latents_original_diffusion, + progress=gr.Progress(track_tqdm=True) +): + kwargs = locals() + + try: + sample, outputs, stats = generate(**kwargs) + except Exception as e: + message = str(e) + if message == "Kill signal detected": + unload_tts() + + raise e + + return ( + outputs[0], + gr.update(value=sample, visible=sample is not None), + gr.update(choices=outputs, value=outputs[0], visible=len(outputs) > 1, interactive=True), + gr.update(value=stats, visible=True), + ) + + +def update_presets(value): + if value in PRESETS: + preset = PRESETS[value] + return (gr.update(value=preset['num_autoregressive_samples']), gr.update(value=preset['diffusion_iterations'])) + else: + return (gr.update(), gr.update()) + +def get_training_configs(): + configs = [] + for i, file in enumerate(sorted(os.listdir(f"./training/"))): + if file[-5:] != ".yaml" or file[0] == ".": + continue + configs.append(f"./training/{file}") + + return configs + +def update_training_configs(): + return gr.update(choices=get_training_list()) + +def history_view_results( voice ): + results = [] + files = [] + outdir = f"{args.results_folder}/{voice}/" + for i, file in enumerate(sorted(os.listdir(outdir))): + if file[-4:] != ".wav": + continue + + metadata, _ = read_generate_settings(f"{outdir}/{file}", read_latents=False) + if metadata is None: + continue + + values = [] + for k in HISTORY_HEADERS: + v = file + if k != "Name": + v = metadata[HISTORY_HEADERS[k]] if HISTORY_HEADERS[k] in metadata else '?' + values.append(v) + + + files.append(file) + results.append(values) + + return ( + results, + gr.Dropdown.update(choices=sorted(files)) + ) + +def import_generate_settings_proxy( file=None ): + global GENERATE_SETTINGS_ARGS + settings = import_generate_settings( file ) + + res = [] + for k in GENERATE_SETTINGS_ARGS: + res.append(settings[k] if k in settings else None) + + return tuple(res) + +def reset_generate_settings_proxy(): + global GENERATE_SETTINGS_ARGS + settings = reset_generate_settings() + + res = [] + for k in GENERATE_SETTINGS_ARGS: + res.append(settings[k] if k in settings else None) + + return tuple(res) + +def compute_latents_proxy(voice, voice_latents_chunks, original_ar, original_diffusion, progress=gr.Progress(track_tqdm=True)): + compute_latents( voice=voice, voice_latents_chunks=voice_latents_chunks, original_ar=original_ar, original_diffusion=original_diffusion ) + return voice + + +def import_voices_proxy(files, name, progress=gr.Progress(track_tqdm=True)): + import_voices(files, name, progress) + return gr.update() + +def read_generate_settings_proxy(file, saveAs='.temp'): + j, latents = read_generate_settings(file) + + if latents: + outdir = f'{get_voice_dir()}/{saveAs}/' + os.makedirs(outdir, exist_ok=True) + with open(f'{outdir}/cond_latents.pth', 'wb') as f: + f.write(latents) + + latents = f'{outdir}/cond_latents.pth' + + return ( + gr.update(value=j, visible=j is not None), + gr.update(value=latents, visible=latents is not None), + None if j is None else j['voice'], + gr.update(visible=j is not None), + ) + +def slice_dataset_proxy( voice, trim_silence, start_offset, end_offset, progress=gr.Progress(track_tqdm=True) ): + return slice_dataset( voice, trim_silence=trim_silence, start_offset=start_offset, end_offset=end_offset, results=None, progress=progress ) + +def diarize_dataset( voice, progress=gr.Progress(track_tqdm=True) ): + from pyannote.audio import Pipeline + pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token=args.hf_token) + + messages = [] + files = get_voice(voice, load_latents=False) + for file in enumerate_progress(files, desc="Iterating through voice files", progress=progress): + diarization = pipeline(file) + for turn, _, speaker in diarization.itertracks(yield_label=True): + message = f"start={turn.start:.1f}s stop={turn.end:.1f}s speaker_{speaker}" + print(message) + messages.append(message) + + return "\n".join(messages) + +def prepare_all_datasets( language, validation_text_length, validation_audio_length, skip_existings, slice_audio, trim_silence, slice_start_offset, slice_end_offset, progress=gr.Progress(track_tqdm=True) ): + kwargs = locals() + + messages = [] + voices = get_voice_list() + + for voice in voices: + print("Processing:", voice) + message = transcribe_dataset( voice=voice, language=language, skip_existings=skip_existings, progress=progress ) + messages.append(message) + + if slice_audio: + for voice in voices: + print("Processing:", voice) + message = slice_dataset( voice, trim_silence=trim_silence, start_offset=slice_start_offset, end_offset=slice_end_offset, results=None, progress=progress ) + messages.append(message) + + for voice in voices: + print("Processing:", voice) + message = prepare_dataset( voice, use_segments=slice_audio, text_length=validation_text_length, audio_length=validation_audio_length, progress=progress ) + messages.append(message) + + return "\n".join(messages) + +def prepare_dataset_proxy( voice, language, validation_text_length, validation_audio_length, skip_existings, slice_audio, trim_silence, slice_start_offset, slice_end_offset, progress=gr.Progress(track_tqdm=True) ): + messages = [] + + message = transcribe_dataset( voice=voice, language=language, skip_existings=skip_existings, progress=progress ) + messages.append(message) + + if slice_audio: + message = slice_dataset( voice, trim_silence=trim_silence, start_offset=slice_start_offset, end_offset=slice_end_offset, results=None, progress=progress ) + messages.append(message) + + message = prepare_dataset( voice, use_segments=slice_audio, text_length=validation_text_length, audio_length=validation_audio_length, progress=progress ) + messages.append(message) + + return "\n".join(messages) + +def update_args_proxy( *args ): + kwargs = {} + keys = list(EXEC_SETTINGS.keys()) + for i in range(len(args)): + k = keys[i] + v = args[i] + kwargs[k] = v + + update_args(**kwargs) +def optimize_training_settings_proxy( *args ): + kwargs = {} + keys = list(TRAINING_SETTINGS.keys()) + for i in range(len(args)): + k = keys[i] + v = args[i] + kwargs[k] = v + + settings, messages = optimize_training_settings(**kwargs) + output = list(settings.values()) + return output[:-1] + ["\n".join(messages)] + +def import_training_settings_proxy( voice ): + messages = [] + injson = f'./training/{voice}/train.json' + statedir = f'./training/{voice}/finetune/training_state/' + output = {} + + try: + with open(injson, 'r', encoding="utf-8") as f: + settings = json.loads(f.read()) + except: + messages.append(f"Error import /{voice}/train.json") + + for k in TRAINING_SETTINGS: + output[k] = TRAINING_SETTINGS[k].value + + output = list(output.values()) + return output[:-1] + ["\n".join(messages)] + + if os.path.isdir(statedir): + resumes = sorted([int(d[:-6]) for d in os.listdir(statedir) if d[-6:] == ".state" ]) + + if len(resumes) > 0: + settings['resume_state'] = f'{statedir}/{resumes[-1]}.state' + messages.append(f"Found most recent training state: {settings['resume_state']}") + + output = {} + for k in TRAINING_SETTINGS: + if k not in settings: + output[k] = gr.update() + else: + output[k] = gr.update(value=settings[k]) + + output = list(output.values()) + + messages.append(f"Imported training settings: {injson}") + + return output[:-1] + ["\n".join(messages)] + +def save_training_settings_proxy( *args ): + kwargs = {} + keys = list(TRAINING_SETTINGS.keys()) + for i in range(len(args)): + k = keys[i] + v = args[i] + kwargs[k] = v + + settings, messages = save_training_settings(**kwargs) + return "\n".join(messages) + +def update_voices(): + return ( + gr.Dropdown.update(choices=get_voice_list(append_defaults=True)), + gr.Dropdown.update(choices=get_voice_list()), + gr.Dropdown.update(choices=get_voice_list(args.results_folder)), + ) + +def history_copy_settings( voice, file ): + return import_generate_settings( f"{args.results_folder}/{voice}/{file}" ) + +def setup_gradio(): + global args + global ui + + if not args.share: + def noop(function, return_value=None): + def wrapped(*args, **kwargs): + return return_value + return wrapped + gradio.utils.version_check = noop(gradio.utils.version_check) + gradio.utils.initiated_analytics = noop(gradio.utils.initiated_analytics) + gradio.utils.launch_analytics = noop(gradio.utils.launch_analytics) + gradio.utils.integration_analytics = noop(gradio.utils.integration_analytics) + gradio.utils.error_analytics = noop(gradio.utils.error_analytics) + gradio.utils.log_feature_analytics = noop(gradio.utils.log_feature_analytics) + #gradio.utils.get_local_ip_address = noop(gradio.utils.get_local_ip_address, 'localhost') + + if args.models_from_local_only: + os.environ['TRANSFORMERS_OFFLINE']='1' + + voice_list_with_defaults = get_voice_list(append_defaults=True) + voice_list = get_voice_list() + result_voices = get_voice_list(args.results_folder) + + valle_models = get_valle_models() + + autoregressive_models = get_autoregressive_models() + diffusion_models = get_diffusion_models() + tokenizer_jsons = get_tokenizer_jsons() + + dataset_list = get_dataset_list() + training_list = get_training_list() + + global GENERATE_SETTINGS_ARGS + GENERATE_SETTINGS_ARGS = list(inspect.signature(generate_proxy).parameters.keys())[:-1] + for i in range(len(GENERATE_SETTINGS_ARGS)): + arg = GENERATE_SETTINGS_ARGS[i] + GENERATE_SETTINGS[arg] = None + + with gr.Blocks() as ui: + with gr.Tab("Generate"): + with gr.Row(): + with gr.Column(): + GENERATE_SETTINGS["text"] = gr.Textbox(lines=4, value="Your prompt here.", label="Input Prompt") + with gr.Row(): + with gr.Column(): + GENERATE_SETTINGS["delimiter"] = gr.Textbox(lines=1, label="Line Delimiter", placeholder="\\n") + + GENERATE_SETTINGS["emotion"] = gr.Radio( ["Happy", "Sad", "Angry", "Disgusted", "Arrogant", "Custom", "None"], value="None", label="Emotion", type="value", interactive=True, visible=args.tts_backend=="tortoise" ) + GENERATE_SETTINGS["prompt"] = gr.Textbox(lines=1, label="Custom Emotion", visible=False) + GENERATE_SETTINGS["voice"] = gr.Dropdown(choices=voice_list_with_defaults, label="Voice", type="value", value=voice_list_with_defaults[0]) # it'd be very cash money if gradio was able to default to the first value in the list without this shit + GENERATE_SETTINGS["mic_audio"] = gr.Audio( label="Microphone Source", source="microphone", type="filepath", visible=False ) + GENERATE_SETTINGS["voice_latents_chunks"] = gr.Number(label="Voice Chunks", precision=0, value=0, visible=args.tts_backend=="tortoise") + GENERATE_SETTINGS["voice_latents_original_ar"] = gr.Checkbox(label="Use Original Latents Method (AR)", visible=args.tts_backend=="tortoise") + GENERATE_SETTINGS["voice_latents_original_diffusion"] = gr.Checkbox(label="Use Original Latents Method (Diffusion)", visible=args.tts_backend=="tortoise") + with gr.Row(): + refresh_voices = gr.Button(value="Refresh Voice List") + recompute_voice_latents = gr.Button(value="(Re)Compute Voice Latents") + + GENERATE_SETTINGS["voice"].change( + fn=update_baseline_for_latents_chunks, + inputs=GENERATE_SETTINGS["voice"], + outputs=GENERATE_SETTINGS["voice_latents_chunks"] + ) + GENERATE_SETTINGS["voice"].change( + fn=lambda value: gr.update(visible=value == "microphone"), + inputs=GENERATE_SETTINGS["voice"], + outputs=GENERATE_SETTINGS["mic_audio"], + ) + with gr.Column(): + preset = None + GENERATE_SETTINGS["candidates"] = gr.Slider(value=1, minimum=1, maximum=6, step=1, label="Candidates", visible=args.tts_backend=="tortoise") + GENERATE_SETTINGS["seed"] = gr.Number(value=0, precision=0, label="Seed", visible=args.tts_backend=="tortoise") + + preset = gr.Radio( ["Ultra Fast", "Fast", "Standard", "High Quality"], label="Preset", type="value", value="Ultra Fast", visible=args.tts_backend=="tortoise" ) + + GENERATE_SETTINGS["num_autoregressive_samples"] = gr.Slider(value=16, minimum=2, maximum=2048 if args.tts_backend=="vall-e" else 512, step=1, label="Samples", visible=args.tts_backend!="bark") + GENERATE_SETTINGS["diffusion_iterations"] = gr.Slider(value=30, minimum=0, maximum=512, step=1, label="Iterations", visible=args.tts_backend=="tortoise") + + GENERATE_SETTINGS["temperature"] = gr.Slider(value=0.95 if args.tts_backend=="vall-e" else 0.2, minimum=0, maximum=1, step=0.05, label="Temperature") + + show_experimental_settings = gr.Checkbox(label="Show Experimental Settings", visible=args.tts_backend=="tortoise") + reset_generate_settings_button = gr.Button(value="Reset to Default") + with gr.Column(visible=False) as col: + experimental_column = col + + GENERATE_SETTINGS["experimentals"] = gr.CheckboxGroup(["Half Precision", "Conditioning-Free"], value=["Conditioning-Free"], label="Experimental Flags") + GENERATE_SETTINGS["breathing_room"] = gr.Slider(value=8, minimum=1, maximum=32, step=1, label="Pause Size") + GENERATE_SETTINGS["diffusion_sampler"] = gr.Radio( + ["P", "DDIM"], # + ["K_Euler_A", "DPM++2M"], + value="DDIM", label="Diffusion Samplers", type="value" + ) + GENERATE_SETTINGS["cvvp_weight"] = gr.Slider(value=0, minimum=0, maximum=1, label="CVVP Weight") + GENERATE_SETTINGS["top_p"] = gr.Slider(value=0.8, minimum=0, maximum=1, label="Top P") + GENERATE_SETTINGS["diffusion_temperature"] = gr.Slider(value=1.0, minimum=0, maximum=1, label="Diffusion Temperature") + GENERATE_SETTINGS["length_penalty"] = gr.Slider(value=1.0, minimum=0, maximum=8, label="Length Penalty") + GENERATE_SETTINGS["repetition_penalty"] = gr.Slider(value=2.0, minimum=0, maximum=8, label="Repetition Penalty") + GENERATE_SETTINGS["cond_free_k"] = gr.Slider(value=2.0, minimum=0, maximum=4, label="Conditioning-Free K") + with gr.Column(): + with gr.Row(): + submit = gr.Button(value="Generate") + stop = gr.Button(value="Stop") + + generation_results = gr.Dataframe(label="Results", headers=["Seed", "Time"], visible=False) + source_sample = gr.Audio(label="Source Sample", visible=False) + output_audio = gr.Audio(label="Output") + candidates_list = gr.Dropdown(label="Candidates", type="value", visible=False, choices=[""], value="") + + def change_candidate( val ): + if not val: + return + return val + + candidates_list.change( + fn=change_candidate, + inputs=candidates_list, + outputs=output_audio, + ) + with gr.Tab("History"): + with gr.Row(): + with gr.Column(): + history_info = gr.Dataframe(label="Results", headers=list(HISTORY_HEADERS.keys())) + with gr.Row(): + with gr.Column(): + history_voices = gr.Dropdown(choices=result_voices, label="Voice", type="value", value=result_voices[0] if len(result_voices) > 0 else "") + with gr.Column(): + history_results_list = gr.Dropdown(label="Results",type="value", interactive=True, value="") + with gr.Column(): + history_audio = gr.Audio() + history_copy_settings_button = gr.Button(value="Copy Settings") + with gr.Tab("Utilities"): + with gr.Tab("Import / Analyze"): + with gr.Row(): + with gr.Column(): + audio_in = gr.Files(type="file", label="Audio Input", file_types=["audio"]) + import_voice_name = gr.Textbox(label="Voice Name") + import_voice_button = gr.Button(value="Import Voice") + with gr.Column(visible=False) as col: + utilities_metadata_column = col + + metadata_out = gr.JSON(label="Audio Metadata") + copy_button = gr.Button(value="Copy Settings") + latents_out = gr.File(type="binary", label="Voice Latents") + with gr.Tab("Tokenizer"): + with gr.Row(): + text_tokenizier_input = gr.TextArea(label="Text", max_lines=4) + text_tokenizier_output = gr.TextArea(label="Tokenized Text", max_lines=4) + + with gr.Row(): + text_tokenizier_button = gr.Button(value="Tokenize Text") + with gr.Tab("Model Merger"): + with gr.Column(): + with gr.Row(): + MERGER_SETTINGS["model_a"] = gr.Dropdown( choices=autoregressive_models, label="Model A", type="value", value=autoregressive_models[0] ) + MERGER_SETTINGS["model_b"] = gr.Dropdown( choices=autoregressive_models, label="Model B", type="value", value=autoregressive_models[0] ) + with gr.Row(): + MERGER_SETTINGS["weight_slider"] = gr.Slider(label="Weight (from A to B)", value=0.5, minimum=0, maximum=1) + with gr.Row(): + merger_button = gr.Button(value="Run Merger") + with gr.Column(): + merger_output = gr.TextArea(label="Console Output", max_lines=8) + with gr.Tab("Training"): + with gr.Tab("Prepare Dataset"): + with gr.Row(): + with gr.Column(): + DATASET_SETTINGS = {} + DATASET_SETTINGS['voice'] = gr.Dropdown( choices=voice_list, label="Dataset Source", type="value", value=voice_list[0] if len(voice_list) > 0 else "" ) + with gr.Row(): + DATASET_SETTINGS['language'] = gr.Textbox(label="Language", value="en") + DATASET_SETTINGS['validation_text_length'] = gr.Number(label="Validation Text Length Threshold", value=12, precision=0, visible=args.tts_backend=="tortoise") + DATASET_SETTINGS['validation_audio_length'] = gr.Number(label="Validation Audio Length Threshold", value=1, visible=args.tts_backend=="tortoise" ) + with gr.Row(): + DATASET_SETTINGS['skip'] = gr.Checkbox(label="Skip Existing", value=False) + DATASET_SETTINGS['slice'] = gr.Checkbox(label="Slice Segments", value=False) + DATASET_SETTINGS['trim_silence'] = gr.Checkbox(label="Trim Silence", value=False) + with gr.Row(): + DATASET_SETTINGS['slice_start_offset'] = gr.Number(label="Slice Start Offset", value=0) + DATASET_SETTINGS['slice_end_offset'] = gr.Number(label="Slice End Offset", value=0) + + transcribe_button = gr.Button(value="Transcribe and Process") + transcribe_all_button = gr.Button(value="Transcribe All") + diarize_button = gr.Button(value="Diarize", visible=False) + + with gr.Row(): + slice_dataset_button = gr.Button(value="(Re)Slice Audio") + prepare_dataset_button = gr.Button(value="(Re)Create Dataset") + + with gr.Row(): + EXEC_SETTINGS['whisper_backend'] = gr.Dropdown(WHISPER_BACKENDS, label="Whisper Backends", value=args.whisper_backend) + EXEC_SETTINGS['whisper_model'] = gr.Dropdown(WHISPER_MODELS, label="Whisper Model", value=args.whisper_model) + + dataset_settings = list(DATASET_SETTINGS.values()) + with gr.Column(): + prepare_dataset_output = gr.TextArea(label="Console Output", interactive=False, max_lines=8) + with gr.Tab("Generate Configuration", visible=args.tts_backend != "bark"): + with gr.Row(): + with gr.Column(): + TRAINING_SETTINGS["epochs"] = gr.Number(label="Epochs", value=500, precision=0) + with gr.Row(visible=args.tts_backend=="tortoise"): + TRAINING_SETTINGS["learning_rate"] = gr.Slider(label="Learning Rate", value=1e-5, minimum=0, maximum=1e-4, step=1e-6) + TRAINING_SETTINGS["mel_lr_weight"] = gr.Slider(label="Mel LR Ratio", value=1.00, minimum=0, maximum=1) + TRAINING_SETTINGS["text_lr_weight"] = gr.Slider(label="Text LR Ratio", value=0.01, minimum=0, maximum=1) + + with gr.Row(visible=args.tts_backend=="tortoise"): + lr_schemes = list(LEARNING_RATE_SCHEMES.keys()) + TRAINING_SETTINGS["learning_rate_scheme"] = gr.Radio(lr_schemes, label="Learning Rate Scheme", value=lr_schemes[0], type="value") + TRAINING_SETTINGS["learning_rate_schedule"] = gr.Textbox(label="Learning Rate Schedule", placeholder=str(LEARNING_RATE_SCHEDULE), visible=True) + TRAINING_SETTINGS["learning_rate_restarts"] = gr.Number(label="Learning Rate Restarts", value=4, precision=0, visible=False) + + TRAINING_SETTINGS["learning_rate_scheme"].change( + fn=lambda x: ( gr.update(visible=x == lr_schemes[0]), gr.update(visible=x == lr_schemes[1]) ), + inputs=TRAINING_SETTINGS["learning_rate_scheme"], + outputs=[ + TRAINING_SETTINGS["learning_rate_schedule"], + TRAINING_SETTINGS["learning_rate_restarts"], + ] + ) + with gr.Row(): + TRAINING_SETTINGS["batch_size"] = gr.Number(label="Batch Size", value=128, precision=0) + TRAINING_SETTINGS["gradient_accumulation_size"] = gr.Number(label="Gradient Accumulation Size", value=4, precision=0) + with gr.Row(): + TRAINING_SETTINGS["save_rate"] = gr.Number(label="Save Frequency (in epochs)", value=5, precision=0) + TRAINING_SETTINGS["validation_rate"] = gr.Number(label="Validation Frequency (in epochs)", value=5, precision=0) + + with gr.Row(): + TRAINING_SETTINGS["half_p"] = gr.Checkbox(label="Half Precision", value=args.training_default_halfp, visible=args.tts_backend=="tortoise") + TRAINING_SETTINGS["bitsandbytes"] = gr.Checkbox(label="BitsAndBytes", value=args.training_default_bnb, visible=args.tts_backend=="tortoise") + TRAINING_SETTINGS["validation_enabled"] = gr.Checkbox(label="Validation Enabled", value=False) + + with gr.Row(): + TRAINING_SETTINGS["workers"] = gr.Number(label="Worker Processes", value=2, precision=0, visible=args.tts_backend=="tortoise") + TRAINING_SETTINGS["gpus"] = gr.Number(label="GPUs", value=get_device_count(), precision=0) + + TRAINING_SETTINGS["source_model"] = gr.Dropdown( choices=autoregressive_models, label="Source Model", type="value", value=autoregressive_models[0], visible=args.tts_backend=="tortoise" ) + TRAINING_SETTINGS["resume_state"] = gr.Textbox(label="Resume State Path", placeholder="./training/${voice}/finetune/training_state/${last_state}.state", visible=args.tts_backend=="tortoise") + + TRAINING_SETTINGS["voice"] = gr.Dropdown( choices=dataset_list, label="Dataset", type="value", value=dataset_list[0] if len(dataset_list) else "" ) + + with gr.Row(): + training_refresh_dataset = gr.Button(value="Refresh Dataset List") + training_import_settings = gr.Button(value="Reuse/Import Dataset") + with gr.Column(): + training_configuration_output = gr.TextArea(label="Console Output", interactive=False, max_lines=8) + with gr.Row(): + training_optimize_configuration = gr.Button(value="Validate Training Configuration") + training_save_configuration = gr.Button(value="Save Training Configuration") + with gr.Tab("Run Training", visible=args.tts_backend != "bark"): + with gr.Row(): + with gr.Column(): + training_configs = gr.Dropdown(label="Training Configuration", choices=training_list, value=training_list[0] if len(training_list) else "") + refresh_configs = gr.Button(value="Refresh Configurations") + training_output = gr.TextArea(label="Console Output", interactive=False, max_lines=8) + verbose_training = gr.Checkbox(label="Verbose Console Output", value=True) + + keep_x_past_checkpoints = gr.Slider(label="Keep X Previous States", minimum=0, maximum=8, value=0, step=1) + + with gr.Row(): + training_graph_x_min = gr.Number(label="X Min", precision=0, value=0) + training_graph_x_max = gr.Number(label="X Max", precision=0, value=0) + training_graph_y_min = gr.Number(label="Y Min", precision=0, value=0) + training_graph_y_max = gr.Number(label="Y Max", precision=0, value=0) + + with gr.Row(): + start_training_button = gr.Button(value="Train") + stop_training_button = gr.Button(value="Stop") + reconnect_training_button = gr.Button(value="Reconnect") + + + with gr.Column(): + training_loss_graph = gr.LinePlot(label="Training Metrics", + x="it", # x="epoch", + y="value", + title="Loss Metrics", + color="type", + tooltip=['epoch', 'it', 'value', 'type'], + width=500, + height=350, + ) + training_lr_graph = gr.LinePlot(label="Training Metrics", + x="it", # x="epoch", + y="value", + title="Learning Rate", + color="type", + tooltip=['epoch', 'it', 'value', 'type'], + width=500, + height=350, + ) + training_grad_norm_graph = gr.LinePlot(label="Training Metrics", + x="it", # x="epoch", + y="value", + title="Gradient Normals", + color="type", + tooltip=['epoch', 'it', 'value', 'type'], + width=500, + height=350, + visible=False, # args.tts_backend=="vall-e" + ) + view_losses = gr.Button(value="View Losses") + + with gr.Tab("Settings"): + with gr.Row(): + exec_inputs = [] + with gr.Column(): + EXEC_SETTINGS['listen'] = gr.Textbox(label="Listen", value=args.listen, placeholder="127.0.0.1:7860/") + EXEC_SETTINGS['share'] = gr.Checkbox(label="Public Share Gradio", value=args.share) + EXEC_SETTINGS['check_for_updates'] = gr.Checkbox(label="Check For Updates", value=args.check_for_updates) + EXEC_SETTINGS['models_from_local_only'] = gr.Checkbox(label="Only Load Models Locally", value=args.models_from_local_only) + EXEC_SETTINGS['low_vram'] = gr.Checkbox(label="Low VRAM", value=args.low_vram) + EXEC_SETTINGS['embed_output_metadata'] = gr.Checkbox(label="Embed Output Metadata", value=args.embed_output_metadata) + EXEC_SETTINGS['latents_lean_and_mean'] = gr.Checkbox(label="Slimmer Computed Latents", value=args.latents_lean_and_mean) + EXEC_SETTINGS['voice_fixer'] = gr.Checkbox(label="Use Voice Fixer on Generated Output", value=args.voice_fixer) + EXEC_SETTINGS['use_deepspeed'] = gr.Checkbox(label="Use DeepSpeed for Speed Bump.", value=args.use_deepspeed) + EXEC_SETTINGS['use_hifigan'] = gr.Checkbox(label="Use Hifigan instead of Diffusion.", value=args.use_hifigan) + EXEC_SETTINGS['voice_fixer_use_cuda'] = gr.Checkbox(label="Use CUDA for Voice Fixer", value=args.voice_fixer_use_cuda) + EXEC_SETTINGS['force_cpu_for_conditioning_latents'] = gr.Checkbox(label="Force CPU for Conditioning Latents", value=args.force_cpu_for_conditioning_latents) + EXEC_SETTINGS['defer_tts_load'] = gr.Checkbox(label="Do Not Load TTS On Startup", value=args.defer_tts_load) + EXEC_SETTINGS['prune_nonfinal_outputs'] = gr.Checkbox(label="Delete Non-Final Output", value=args.prune_nonfinal_outputs) + with gr.Column(): + EXEC_SETTINGS['sample_batch_size'] = gr.Number(label="Sample Batch Size", precision=0, value=args.sample_batch_size) + EXEC_SETTINGS['unsqueeze_sample_batches'] = gr.Checkbox(label="Unsqueeze Sample Batches", value=args.unsqueeze_sample_batches) + EXEC_SETTINGS['concurrency_count'] = gr.Number(label="Gradio Concurrency Count", precision=0, value=args.concurrency_count) + EXEC_SETTINGS['autocalculate_voice_chunk_duration_size'] = gr.Number(label="Auto-Calculate Voice Chunk Duration (in seconds)", precision=0, value=args.autocalculate_voice_chunk_duration_size) + EXEC_SETTINGS['output_volume'] = gr.Slider(label="Output Volume", minimum=0, maximum=2, value=args.output_volume) + EXEC_SETTINGS['device_override'] = gr.Textbox(label="Device Override", value=args.device_override) + + EXEC_SETTINGS['results_folder'] = gr.Textbox(label="Results Folder", value=args.results_folder) + # EXEC_SETTINGS['tts_backend'] = gr.Dropdown(TTSES, label="TTS Backend", value=args.tts_backend if args.tts_backend else TTSES[0]) + + if args.tts_backend=="vall-e": + with gr.Column(): + EXEC_SETTINGS['valle_model'] = gr.Dropdown(choices=valle_models, label="VALL-E Model Config", value=args.valle_model if args.valle_model else valle_models[0]) + + with gr.Column(visible=args.tts_backend=="tortoise"): + EXEC_SETTINGS['autoregressive_model'] = gr.Dropdown(choices=["auto"] + autoregressive_models, label="Autoregressive Model", value=args.autoregressive_model if args.autoregressive_model else "auto") + EXEC_SETTINGS['diffusion_model'] = gr.Dropdown(choices=diffusion_models, label="Diffusion Model", value=args.diffusion_model if args.diffusion_model else diffusion_models[0]) + EXEC_SETTINGS['vocoder_model'] = gr.Dropdown(VOCODERS, label="Vocoder", value=args.vocoder_model if args.vocoder_model else VOCODERS[-1]) + EXEC_SETTINGS['tokenizer_json'] = gr.Dropdown(tokenizer_jsons, label="Tokenizer JSON Path", value=args.tokenizer_json if args.tokenizer_json else tokenizer_jsons[0]) + + EXEC_SETTINGS['training_default_halfp'] = TRAINING_SETTINGS['half_p'] + EXEC_SETTINGS['training_default_bnb'] = TRAINING_SETTINGS['bitsandbytes'] + + with gr.Row(): + autoregressive_models_update_button = gr.Button(value="Refresh Model List") + gr.Button(value="Check for Updates").click(check_for_updates) + gr.Button(value="(Re)Load TTS").click( + reload_tts, + inputs=None, + outputs=None + ) + # kill_button = gr.Button(value="Close UI") + + def update_model_list_proxy( autoregressive, diffusion, tokenizer ): + autoregressive_models = get_autoregressive_models() + if autoregressive not in autoregressive_models: + autoregressive = autoregressive_models[0] + + diffusion_models = get_diffusion_models() + if diffusion not in diffusion_models: + diffusion = diffusion_models[0] + + tokenizer_jsons = get_tokenizer_jsons() + if tokenizer not in tokenizer_jsons: + tokenizer = tokenizer_jsons[0] + + return ( + gr.update( choices=autoregressive_models, value=autoregressive ), + gr.update( choices=diffusion_models, value=diffusion ), + gr.update( choices=tokenizer_jsons, value=tokenizer ), + ) + + autoregressive_models_update_button.click( + update_model_list_proxy, + inputs=[ + EXEC_SETTINGS['autoregressive_model'], + EXEC_SETTINGS['diffusion_model'], + EXEC_SETTINGS['tokenizer_json'], + ], + outputs=[ + EXEC_SETTINGS['autoregressive_model'], + EXEC_SETTINGS['diffusion_model'], + EXEC_SETTINGS['tokenizer_json'], + ], + ) + + exec_inputs = list(EXEC_SETTINGS.values()) + for k in EXEC_SETTINGS: + EXEC_SETTINGS[k].change( fn=update_args_proxy, inputs=exec_inputs ) + + EXEC_SETTINGS['autoregressive_model'].change( + fn=update_autoregressive_model, + inputs=EXEC_SETTINGS['autoregressive_model'], + outputs=None, + api_name="set_autoregressive_model" + ) + + EXEC_SETTINGS['vocoder_model'].change( + fn=update_vocoder_model, + inputs=EXEC_SETTINGS['vocoder_model'], + outputs=None + ) + + history_voices.change( + fn=history_view_results, + inputs=history_voices, + outputs=[ + history_info, + history_results_list, + ] + ) + history_results_list.change( + fn=lambda voice, file: f"{args.results_folder}/{voice}/{file}", + inputs=[ + history_voices, + history_results_list, + ], + outputs=history_audio + ) + audio_in.upload( + fn=read_generate_settings_proxy, + inputs=audio_in, + outputs=[ + metadata_out, + latents_out, + import_voice_name, + utilities_metadata_column, + ] + ) + + import_voice_button.click( + fn=import_voices_proxy, + inputs=[ + audio_in, + import_voice_name, + ], + outputs=import_voice_name #console_output + ) + show_experimental_settings.change( + fn=lambda x: gr.update(visible=x), + inputs=show_experimental_settings, + outputs=experimental_column + ) + if preset: + preset.change(fn=update_presets, + inputs=preset, + outputs=[ + GENERATE_SETTINGS['num_autoregressive_samples'], + GENERATE_SETTINGS['diffusion_iterations'], + ], + ) + + recompute_voice_latents.click(compute_latents_proxy, + inputs=[ + GENERATE_SETTINGS['voice'], + GENERATE_SETTINGS['voice_latents_chunks'], + GENERATE_SETTINGS['voice_latents_original_ar'], + GENERATE_SETTINGS['voice_latents_original_diffusion'], + ], + outputs=GENERATE_SETTINGS['voice'], + ) + + GENERATE_SETTINGS['emotion'].change( + fn=lambda value: gr.update(visible=value == "Custom"), + inputs=GENERATE_SETTINGS['emotion'], + outputs=GENERATE_SETTINGS['prompt'] + ) + GENERATE_SETTINGS['mic_audio'].change(fn=lambda value: gr.update(value="microphone"), + inputs=GENERATE_SETTINGS['mic_audio'], + outputs=GENERATE_SETTINGS['voice'] + ) + + refresh_voices.click(update_voices, + inputs=None, + outputs=[ + GENERATE_SETTINGS['voice'], + DATASET_SETTINGS['voice'], + history_voices + ] + ) + + generate_settings = list(GENERATE_SETTINGS.values()) + submit.click( + lambda: (gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)), + outputs=[source_sample, candidates_list, generation_results], + ) + + submit_event = submit.click(generate_proxy, + inputs=generate_settings, + outputs=[output_audio, source_sample, candidates_list, generation_results], + api_name="generate", + ) + + + copy_button.click(import_generate_settings_proxy, + inputs=audio_in, # JSON elements cannot be used as inputs + outputs=generate_settings + ) + + reset_generate_settings_button.click( + fn=reset_generate_settings_proxy, + inputs=None, + outputs=generate_settings + ) + + history_copy_settings_button.click(history_copy_settings, + inputs=[ + history_voices, + history_results_list, + ], + outputs=generate_settings + ) + + text_tokenizier_button.click(tokenize_text, + inputs=text_tokenizier_input, + outputs=text_tokenizier_output + ) + + merger_button.click(merge_models, + inputs=list(MERGER_SETTINGS.values()), + outputs=merger_output + ) + + refresh_configs.click( + lambda: gr.update(choices=get_training_list()), + inputs=None, + outputs=training_configs + ) + start_training_button.click(run_training, + inputs=[ + training_configs, + verbose_training, + keep_x_past_checkpoints, + ], + outputs=[ + training_output, + ], + ) + training_output.change( + fn=update_training_dataplot, + inputs=[ + training_graph_x_min, + training_graph_x_max, + training_graph_y_min, + training_graph_y_max, + ], + outputs=[ + training_loss_graph, + training_lr_graph, + training_grad_norm_graph, + ], + show_progress=False, + ) + + view_losses.click( + fn=update_training_dataplot, + inputs=[ + training_graph_x_min, + training_graph_x_max, + training_graph_y_min, + training_graph_y_max, + training_configs, + ], + outputs=[ + training_loss_graph, + training_lr_graph, + training_grad_norm_graph, + ], + ) + + stop_training_button.click(stop_training, + inputs=None, + outputs=training_output #console_output + ) + reconnect_training_button.click(reconnect_training, + inputs=[ + verbose_training, + ], + outputs=training_output #console_output + ) + transcribe_button.click( + prepare_dataset_proxy, + inputs=dataset_settings, + outputs=prepare_dataset_output #console_output + ) + transcribe_all_button.click( + prepare_all_datasets, + inputs=dataset_settings[1:], + outputs=prepare_dataset_output #console_output + ) + diarize_button.click( + diarize_dataset, + inputs=dataset_settings[0], + outputs=prepare_dataset_output #console_output + ) + prepare_dataset_button.click( + prepare_dataset, + inputs=[ + DATASET_SETTINGS['voice'], + DATASET_SETTINGS['slice'], + DATASET_SETTINGS['validation_text_length'], + DATASET_SETTINGS['validation_audio_length'], + ], + outputs=prepare_dataset_output #console_output + ) + slice_dataset_button.click( + slice_dataset_proxy, + inputs=[ + DATASET_SETTINGS['voice'], + DATASET_SETTINGS['trim_silence'], + DATASET_SETTINGS['slice_start_offset'], + DATASET_SETTINGS['slice_end_offset'], + ], + outputs=prepare_dataset_output + ) + + training_refresh_dataset.click( + lambda: gr.update(choices=get_dataset_list()), + inputs=None, + outputs=TRAINING_SETTINGS["voice"], + ) + training_settings = list(TRAINING_SETTINGS.values()) + training_optimize_configuration.click(optimize_training_settings_proxy, + inputs=training_settings, + outputs=training_settings[:-1] + [training_configuration_output] #console_output + ) + training_import_settings.click(import_training_settings_proxy, + inputs=TRAINING_SETTINGS['voice'], + outputs=training_settings[:-1] + [training_configuration_output] #console_output + ) + training_save_configuration.click(save_training_settings_proxy, + inputs=training_settings, + outputs=training_configuration_output #console_output + ) + + if os.path.isfile('./config/generate.json'): + ui.load(import_generate_settings_proxy, inputs=None, outputs=generate_settings) + + if args.check_for_updates: + ui.load(check_for_updates) + + stop.click(fn=cancel_generate, inputs=None, outputs=None) + + + ui.queue(concurrency_count=args.concurrency_count) + webui = ui + return webui \ No newline at end of file diff --git a/start-docker.sh b/start-docker.sh new file mode 100644 index 0000000..b11279f --- /dev/null +++ b/start-docker.sh @@ -0,0 +1,14 @@ +#!/bin/bash +CMD="python3 ./src/main.py $@" +# CMD="bash" +CPATH="/home/user/ai-voice-cloning" +docker run --rm --gpus all \ + --mount "type=bind,src=$PWD/models,dst=$CPATH/models" \ + --mount "type=bind,src=$PWD/training,dst=$CPATH/training" \ + --mount "type=bind,src=$PWD/voices,dst=$CPATH/voices" \ + --mount "type=bind,src=$PWD/bin,dst=$CPATH/bin" \ + --workdir $CPATH \ + --user "$(id -u):$(id -g)" \ + --net host \ + -it ai-voice-cloning $CMD + diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..186cd96 --- /dev/null +++ b/start.bat @@ -0,0 +1,5 @@ +call .\venv\Scripts\activate.bat +set PATH=.\bin\;%PATH% +set PYTHONUTF8=1 +python .\src\main.py %* +pause \ No newline at end of file diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..e0ac548 --- /dev/null +++ b/start.sh @@ -0,0 +1,5 @@ +#!/bin/bash +ulimit -Sn `ulimit -Hn` # ROCm is a bitch +source ./venv/bin/activate +python3 ./src/main.py "$@" +deactivate diff --git a/train-docker.sh b/train-docker.sh new file mode 100644 index 0000000..cd19b1a --- /dev/null +++ b/train-docker.sh @@ -0,0 +1,15 @@ +#!/bin/bash +CMD="python3 ./src/train.py --yaml $1" +# ipc host is one way to increase the shared memory for the container +# more info here https://github.com/pytorch/pytorch#docker-image +CPATH="/home/user/ai-voice-cloning" +docker run --rm --gpus all \ + --mount "type=bind,src=$PWD/models,dst=$CPATH/models" \ + --mount "type=bind,src=$PWD/training,dst=$CPATH/training" \ + --mount "type=bind,src=$PWD/voices,dst=$CPATH/voices" \ + --mount "type=bind,src=$PWD/bin,dst=$CPATH/bin" \ + --mount "type=bind,src=$PWD/src,dst=$CPATH/src" \ + --workdir $CPATH \ + --ipc host \ + --user "$(id -u):$(id -g)" \ + -it ai-voice-cloning $CMD diff --git a/train.bat b/train.bat new file mode 100644 index 0000000..a019311 --- /dev/null +++ b/train.bat @@ -0,0 +1,5 @@ +call .\venv\Scripts\activate.bat +set PYTHONUTF8=1 +python ./src/train.py --yaml "%1" +pause +deactivate \ No newline at end of file diff --git a/train.sh b/train.sh new file mode 100644 index 0000000..b112e45 --- /dev/null +++ b/train.sh @@ -0,0 +1,4 @@ +#!/bin/bash +source ./venv/bin/activate +python3 ./src/train.py --yaml "$1" +deactivate diff --git a/training/.gitignore b/training/.gitignore new file mode 100644 index 0000000..c96a04f --- /dev/null +++ b/training/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/update-force.bat b/update-force.bat new file mode 100644 index 0000000..3bb5607 --- /dev/null +++ b/update-force.bat @@ -0,0 +1,15 @@ +git fetch --all +git reset --hard origin/master +call .\update.bat + +python -m venv venv +call .\venv\Scripts\activate.bat + +python -m pip install --upgrade pip +python -m pip install -U -r .\modules\tortoise-tts\requirements.txt +python -m pip install -U -e .\modules\tortoise-tts +python -m pip install -U -r .\modules\dlas\requirements.txt +python -m pip install -U -r .\requirements.txt + +pause +deactivate \ No newline at end of file diff --git a/update-force.sh b/update-force.sh new file mode 100644 index 0000000..829e946 --- /dev/null +++ b/update-force.sh @@ -0,0 +1,18 @@ +#!/bin/bash +git fetch --all +git reset --hard origin/master + +./update.sh + +# force install requirements +python3 -m venv venv +source ./venv/bin/activate + +python3 -m pip install --upgrade pip +python3 -m pip install -r ./modules/tortoise-tts/requirements.txt +python3 -m pip install -e ./modules/tortoise-tts +python3 -m pip install -r ./modules/dlas/requirements.txt +python3 -m pip install -e ./modules/dlas +python3 -m pip install -r ./requirements.txt + +deactivate \ No newline at end of file diff --git a/update.bat b/update.bat new file mode 100644 index 0000000..6c58604 --- /dev/null +++ b/update.bat @@ -0,0 +1,2 @@ +git pull +git submodule update --remote \ No newline at end of file diff --git a/update.sh b/update.sh new file mode 100644 index 0000000..777ba35 --- /dev/null +++ b/update.sh @@ -0,0 +1,7 @@ +#!/bin/bash +git pull +git submodule update --remote + +source ./venv/bin/activate +if python -m pip show whispercpp &>/dev/null; then python -m pip install -U git+https://git.ecker.tech/lightmare/whispercpp.py; fi +deactivate \ No newline at end of file diff --git a/voices/.gitignore b/voices/.gitignore new file mode 100644 index 0000000..c5fcd8b --- /dev/null +++ b/voices/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!.random/ \ No newline at end of file diff --git a/voices/random/cond_latents_d1f79232.pth b/voices/random/cond_latents_d1f79232.pth new file mode 100644 index 0000000..a5527c4 Binary files /dev/null and b/voices/random/cond_latents_d1f79232.pth differ diff --git a/voices/random/cond_latents_f540259e.pth b/voices/random/cond_latents_f540259e.pth new file mode 100644 index 0000000..675dd77 Binary files /dev/null and b/voices/random/cond_latents_f540259e.pth differ