diff --git a/API_DOCS.md b/API_DOCS.md new file mode 100644 index 00000000..6de0eb31 --- /dev/null +++ b/API_DOCS.md @@ -0,0 +1,151 @@ +# StyleTTS2 HTTP Streaming API Documentation + +## Overview + +The HTTP Streaming API provides text-to-speech synthesis with real-time audio streaming. The server uses Flask and returns WAV audio data. + +## Base URL + +``` +http://localhost:5000 +``` + +## Endpoints + +### GET / + +Returns API documentation in HTML format. + +--- + +### POST /api/v1/stream + +Synthesizes speech from text with streaming audio response. + +**Request Body (form-data):** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `text` | string | Yes | Text to synthesize | +| `voice` | string | Yes | Voice ID (see available voices below) | +| `steps` | integer | No | Diffusion steps (default: 7, higher = better quality) | + +**Response:** +- Content-Type: `audio/x-wav` +- Streams WAV audio data in chunks + +**Example with curl:** + +```bash +curl -X POST http://localhost:5000/api/v1/stream \ + -d "text=Hello, this is a test of the streaming API." \ + -d "voice=f-us-1" \ + -d "steps=7" \ + --output output.wav +``` + +**Example with Python:** + +```python +import requests + +response = requests.post( + "http://localhost:5000/api/v1/stream", + data={ + "text": "Hello, this is a test.", + "voice": "f-us-1", + "steps": 7 + }, + stream=True +) + +with open("output.wav", "wb") as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) +``` + +--- + +### POST /api/v1/static + +Synthesizes speech from text and returns complete audio file. + +**Request Body (form-data):** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `text` | string | Yes | Text to synthesize | +| `voice` | string | Yes | Voice ID | + +**Response:** +- Content-Type: `audio/wav` +- Returns complete WAV file + +**Example:** + +```bash +curl -X POST http://localhost:5000/api/v1/static \ + -d "text=Hello world" \ + -d "voice=m-us-1" \ + --output output.wav +``` + +--- + +## Available Voices + +| Voice ID | Description | +|----------|-------------| +| `f-us-1` | Female US English #1 | +| `f-us-2` | Female US English #2 | +| `f-us-3` | Female US English #3 | +| `f-us-4` | Female US English #4 | +| `m-us-1` | Male US English #1 | +| `m-us-2` | Male US English #2 | +| `m-us-3` | Male US English #3 | +| `m-us-4` | Male US English #4 | + +--- + +## Error Responses + +All errors return JSON with an `error` field: + +```json +{ + "error": "Missing required fields. Please include \"text\" and \"voice\" in your request." +} +``` + +**Common errors:** +- `400`: Missing required fields or invalid voice selection + +--- + +## Testing + +Use the provided test client: + +```bash +# List available voices +python test_api_client.py --list-voices + +# Check server status +python test_api_client.py --check-server + +# Synthesize speech +python test_api_client.py -t "Hello world" -v f-us-1 -o output.wav + +# With custom diffusion steps +python test_api_client.py -t "Hello world" -v m-us-2 -o output.wav -s 10 +``` + +--- + +## Starting the Server + +```bash +python api.py +``` + +The server starts on `http://0.0.0.0:5000` by default. \ No newline at end of file diff --git a/LICENSE b/LICENSE index 0c7bc2e1..94a9ed02 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,674 @@ -MIT License - -Copyright (c) 2023 Aaron (Yinghao) Li - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 9caafa70..0fc36d85 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,11 @@ -# StyleTTS 2: Towards Human-Level Text-to-Speech through Style Diffusion and Adversarial Training with Large Speech Language Models +# StyleTTS 2 API -### Yinghao Aaron Li, Cong Han, Vinay S. Raghavan, Gavin Mischler, Nima Mesgarani +[Original Repo](https://github.com/yl4579/StyleTTS2) - [CLI Tool](https://github.com/fakerybakery/styletTS2-cli) - **Streaming API** + +(GPL licensed due to Phonemizer. Should I switch to OpenPhonemizer and make it MIT-licensed?) + + +StyleTTS 2 is by Yinghao Aaron Li, Cong Han, Vinay S. Raghavan, Gavin Mischler, Nima Mesgarani. I am not affiliated with them. > In this paper, we present StyleTTS 2, a text-to-speech (TTS) model that leverages style diffusion and adversarial training with large speech language models (SLMs) to achieve human-level TTS synthesis. StyleTTS 2 differs from its predecessor by modeling styles as a latent random variable through diffusion models to generate the most suitable style for the text without requiring reference speech, achieving efficient latent diffusion while benefiting from the diverse speech synthesis offered by diffusion models. Furthermore, we employ large pre-trained SLMs, such as WavLM, as discriminators with our novel differentiable duration modeling for end-to-end training, resulting in improved speech naturalness. StyleTTS 2 surpasses human recordings on the single-speaker LJSpeech dataset and matches it on the multispeaker VCTK dataset as judged by native English speakers. Moreover, when trained on the LibriTTS dataset, our model outperforms previous publicly available models for zero-shot speaker adaptation. This work achieves the first human-level TTS synthesis on both single and multispeaker datasets, showcasing the potential of style diffusion and adversarial training with large SLMs. @@ -17,7 +22,11 @@ Online demo: [Hugging Face](https://huggingface.co/spaces/styletts2/styletts2) ( - [x] Test training code for multi-speaker models (VCTK and LibriTTS) - [x] Finish demo code for multispeaker model and upload pre-trained models - [x] Add a finetuning script for new speakers with base pre-trained multispeaker models +- [x] REST API +- [x] Importable inference script (PR #78) +- [x] Streaming API and WebSocket support - [ ] Fix DDP (accelerator) for `train_second.py` **(I have tried everything I could to fix this but had no success, so if you are willing to help, please see [#7](https://github.com/yl4579/StyleTTS2/issues/7))** +- [ ] Pip package ## Pre-requisites 1. Python >= 3.7 @@ -42,6 +51,114 @@ sudo apt-get install espeak-ng 4. Download and extract the [LJSpeech dataset](https://keithito.com/LJ-Speech-Dataset/), unzip to the data folder and upsample the data to 24 kHz. The text aligner and pitch extractor are pre-trained on 24 kHz data, but you can easily change the preprocessing and re-train them using your own preprocessing. For LibriTTS, you will need to combine train-clean-360 with train-clean-100 and rename the folder train-clean-460 (see [val_list_libritts.txt](https://github.com/yl4579/StyleTTS/blob/main/Data/val_list_libritts.txt) as an example). +## Streaming API + +You can use StyleTTS 2 in your projects by launching the HTTP API with streaming support. Synthesize text from your frontend apps, etc by making HTTP calls to the API server. The server uses Flask. + +API documentation may be found in the [`API_DOCS.md`](API_DOCS.md) file. + +Launch server: + +```bash +python api.py +``` + +## WebSocket API + +For real-time TTS streaming with chunked text input and low-latency audio output, use the WebSocket API powered by FastAPI. + +**Features:** +- Real-time bidirectional communication +- Chunked text input (send text incrementally) +- Base64-encoded MP3 audio output +- GPU queue management for concurrent requests +- Idle timeout and connection management + +**Quick Start:** + +```bash +# Start WebSocket server (default port 8765) +python ws_server.py + +# Or with custom port +python ws_server.py 9000 +``` + +**Endpoints:** +- WebSocket: `ws://localhost:8765/ws/tts` +- Health Check: `http://localhost:8765/health` +- Voice List: `http://localhost:8765/voices` + +**Test the WebSocket API:** + +```bash +# Simple test +python test_ws_client.py --text "Hello world" --voice f-us-1 --output output.mp3 + +# Chunked streaming test +python test_ws_client.py --text "This is a longer text" --voice m-us-2 --chunked +``` + +Full WebSocket documentation: [`WEBSOCKET_DOCS.md`](WEBSOCKET_DOCS.md) + +## Python API + +You can now use StyleTTS 2 directly in your programs! A `pip`-compatible package is coming soon. + +Multi-Speaker Inference: + +```python +from scipy.io.wavfile import write +import msinference +text = 'Hello world!' +voice = msinference.compute_style('voice.wav') +wav = msinference.inference(text, voice, alpha=0.3, beta=0.7, diffusion_steps=7, embedding_scale=1) +write('result.wav', 24000, wav) +``` + +LJSpeech Inference: + +```python +from scipy.io.wavfile import write +import ljinference +text = 'Hello world!' +noise = torch.randn(1,1,256).to('cuda' if torch.cuda.is_available() else 'cpu') +wav = ljinference.inference(text, noise, diffusion_steps=7, embedding_scale=1) +write('result.wav', 24000, wav) +``` + +For longer text, you can [help implement #54](https://github.com/yl4579/StyleTTS2/issues/54) or use Tortoise TTS for splitting: + +```python +from tortoise.utils.text import split_and_recombine_text +import numpy as np +from scipy.io.wavfile import write +import msinference +text = 'Long text here...' +texts = split_and_recombine_text(text) +audios = [] +voice = msinference.compute_style('voice.wav') +for t in texts: + audios.append(msinference.inference(t, voice, alpha=0.3, beta=0.7, diffusion_steps=7, embedding_scale=1)) +write('result.wav', 24000, np.concatenate(audios)) +``` + +## GUI + +You can run inference (finetuning coming soon) on a GUI based on the [online demo](https://huggingface.co/spaces/styletts2/styletts2) powered by Gradio. + +```bash +python app.py +``` + +**NOTE: Only the multi-speaker tab supports long-text currently.** + +Note: the online demo will be updated more frequently as changes are pushed directly to it (rather than through PRs). If you would like to use the latest (potentially unstable) version, use Docker: + +```bash +docker run -it -p 7860:7860 --platform=linux/amd64 --gpus all registry.hf.space/styletts2-styletts2:latest python app.py +``` + ## Training First stage training: ```bash @@ -117,3 +234,42 @@ You can import StyleTTS 2 and run it in your own code. However, the inference de - [jik876/hifi-gan](https://github.com/jik876/hifi-gan) - [rishikksh20/iSTFTNet-pytorch](https://github.com/rishikksh20/iSTFTNet-pytorch) - [nii-yamagishilab/project-NN-Pytorch-scripts/project/01-nsf](https://github.com/nii-yamagishilab/project-NN-Pytorch-scripts/tree/master/project/01-nsf) + +## License + +**NOTE: By contributing to this software you agree that the license may be changed in the future once I find a phonemizer replacement.** + +This package depends on `phonemizer`, which is GPL licensed. [Check out the original repository for a MIT-licensed version w/o the API!](https://github.com/yl4579/StyleTTS2). I'm working on a permissively licensed Phonemizer - coming soon! + +NOTE: By contributing to this project you agree that the authors may change the license in the future + +Copyright (C) 2023 Aaron (Yinghao) Li (under the MIT license). +Modifications copyright (C) 2023-2024 mrfakename. + +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. + +**This software was previously licensed under the MIT license:** + +MIT License + +Copyright (c) 2023 Aaron (Yinghao) Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/WEBSOCKET_DOCS.md b/WEBSOCKET_DOCS.md new file mode 100644 index 00000000..304a5aff --- /dev/null +++ b/WEBSOCKET_DOCS.md @@ -0,0 +1,235 @@ +# StyleTTS2 WebSocket API Documentation + +## Overview + +The WebSocket API provides real-time text-to-speech streaming with bidirectional communication. It supports chunked text input and returns base64-encoded MP3 audio. + +## Quick Start + +```bash +# Start WebSocket server +python ws_server.py + +# Test with client +python test_ws_client.py --text "Hello world" --voice f-us-1 +``` + +## Endpoints + +### WebSocket: `/ws/tts` + +``` +ws://localhost:8765/ws/tts +``` + +### REST: `/health` + +Health check endpoint. + +```bash +curl http://localhost:8765/health +``` + +Response: +```json +{ + "status": "healthy", + "ready": true, + "stats": { + "queue_size": 0, + "total_requests": 10, + "failed_requests": 0, + "success_rate": 1.0 + } +} +``` + +### REST: `/voices` + +List available voices. + +```bash +curl http://localhost:8765/voices +``` + +Response: +```json +{ + "voices": ["f-us-1", "f-us-2", "f-us-3", "f-us-4", "m-us-1", "m-us-2", "m-us-3", "m-us-4"] +} +``` + +## WebSocket Message Format + +### Input (Client → Server) + +```json +{ + "text": "Text to synthesize", + "voice": "f-us-1", + "flush": true +} +``` + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `text` | string | Yes | Text chunk to synthesize | +| `voice` | string | No | Voice ID (default: f-us-1) | +| `flush` | boolean | No | Set `true` to generate audio from buffered text | + +### Output (Server → Client) + +**Audio response:** +```json +{ + "audio": "base64_encoded_mp3_data", + "isFinal": false +} +``` + +**Welcome message (on connect):** +```json +{ + "status": "connected", + "available_voices": ["f-us-1", ...], + "message": "Send text chunks with 'flush: true' to generate audio" +} +``` + +**Error response:** +```json +{ + "error": "Error message", + "isFinal": true +} +``` + +## Available Voices + +| Voice ID | Description | +|----------|-------------| +| `f-us-1` to `f-us-4` | Female US English | +| `m-us-1` to `m-us-4` | Male US English | + +## Usage Patterns + +### Single Text (Simple) + +Send all text at once with `flush: true`: + +```python +await websocket.send(json.dumps({ + "text": "Hello, this is a complete sentence.", + "voice": "f-us-1", + "flush": True +})) +``` + +### Chunked Streaming (Real-time) + +Buffer text chunks, then flush to generate audio: + +```python +# Send chunks without flushing +await websocket.send(json.dumps({"text": "Hello, ", "voice": "f-us-1", "flush": False})) +await websocket.send(json.dumps({"text": "this is ", "flush": False})) +await websocket.send(json.dumps({"text": "streaming.", "flush": True})) # Flush to generate +``` + +## Code Examples + +### Python + +```python +import asyncio +import websockets +import json +import base64 + +async def synthesize(text, voice="f-us-1"): + uri = "ws://localhost:8765/ws/tts" + async with websockets.connect(uri) as ws: + # Receive welcome + await ws.recv() + + # Send text + await ws.send(json.dumps({ + "text": text, + "voice": voice, + "flush": True + })) + + # Receive audio + audio_chunks = [] + while True: + response = json.loads(await ws.recv()) + if "audio" in response and response["audio"]: + audio_chunks.append(base64.b64decode(response["audio"])) + if response.get("isFinal"): + break + + # Save audio + with open("output.mp3", "wb") as f: + f.write(b"".join(audio_chunks)) + +asyncio.run(synthesize("Hello world")) +``` + +### JavaScript + +```javascript +const ws = new WebSocket('ws://localhost:8765/ws/tts'); + +ws.onopen = () => { + ws.send(JSON.stringify({ + text: 'Hello world', + voice: 'f-us-1', + flush: true + })); +}; + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.audio) { + // Decode base64 and play audio + const audioBytes = atob(data.audio); + // ... play audio + } + if (data.isFinal) { + ws.close(); + } +}; +``` + +## Configuration + +Default settings in `ws_server.py`: + +| Setting | Default | Description | +|---------|---------|-------------| +| Port | 8765 | WebSocket server port | +| Idle timeout | 120s | Connection idle timeout | +| Max queue | 100 | Maximum pending requests | +| Ping interval | 20s | WebSocket keepalive | + +## Testing + +```bash +# Simple test +python test_ws_client.py --text "Hello" --voice f-us-1 --output test.mp3 + +# Chunked streaming test +python test_ws_client.py --text "Long text here" --chunked + +# Custom server +python test_ws_client.py --uri ws://192.168.1.100:8765/ws/tts --text "Hello" +``` + +## Error Handling + +| Error | Cause | Solution | +|-------|-------|----------| +| Invalid voice | Voice ID not recognized | Use voice from `/voices` endpoint | +| Queue full | Too many pending requests | Retry after delay | +| Connection timeout | Idle for 2+ minutes | Reconnect | +| Invalid JSON | Malformed message | Check JSON syntax | diff --git a/api.py b/api.py new file mode 100644 index 00000000..160a0531 --- /dev/null +++ b/api.py @@ -0,0 +1,171 @@ +# StyleTTS 2 HTTP Streaming API by @fakerybakery - Copyright (c) 2023 mrfakename. All rights reserved. +# Docs: API_DOCS.md +# To-Do: +# * Support voice cloning +# * Implement authentication, user "credits" system w/ SQLite3 +import io +import markdown +from tortoise.utils.text import split_and_recombine_text +from flask import Flask, Response, request, jsonify +from scipy.io.wavfile import write +import phonemizer +import numpy as np +import ljinference +import msinference +import torch +from flask_cors import CORS + +# Download required NLTK data +import nltk + +try: + nltk.data.find("tokenizers/punkt_tab") +except LookupError: + nltk.download("punkt_tab", quiet=True) + + +def genHeader(sampleRate, bitsPerSample, channels): + datasize = 2000 * 10**6 + o = bytes("RIFF", "ascii") + o += (datasize + 36).to_bytes(4, "little") + o += bytes("WAVE", "ascii") + o += bytes("fmt ", "ascii") + o += (16).to_bytes(4, "little") + o += (1).to_bytes(2, "little") + o += (channels).to_bytes(2, "little") + o += (sampleRate).to_bytes(4, "little") + o += (sampleRate * channels * bitsPerSample // 8).to_bytes(4, "little") + o += (channels * bitsPerSample // 8).to_bytes(2, "little") + o += (bitsPerSample).to_bytes(2, "little") + o += bytes("data", "ascii") + o += (datasize).to_bytes(4, "little") + return o + + +voicelist = [ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", +] +voices = {} + +global_phonemizer = phonemizer.backend.EspeakBackend( + language="en-us", preserve_punctuation=True, with_stress=True +) +print("Computing voices") +for v in voicelist: + voices[v] = msinference.compute_style(f"voices/{v}.wav") +print("Starting Flask app") + +app = Flask(__name__) +cors = CORS(app) + + +@app.route("/") +def index(): + with open("API_DOCS.md", "r") as f: + return markdown.markdown(f.read()) + + +def synthesize(text, voice, steps): + v = voice.lower() + return msinference.inference( + text, voices[v], alpha=0.3, beta=0.7, diffusion_steps=steps, embedding_scale=1 + ) + + +def ljsynthesize(text, steps): + return ljinference.inference( + text, + torch.randn(1, 1, 256).to("cuda" if torch.cuda.is_available() else "cpu"), + diffusion_steps=steps, + embedding_scale=1, + ) + + +@app.route("/api/v1/stream", methods=["POST"]) +def serve_wav_stream(): + if "text" not in request.form or "voice" not in request.form: + error_response = { + "error": 'Missing required fields. Please include "text" and "voice" in your request.' + } + return jsonify(error_response), 400 + text = request.form["text"].strip() + voice = request.form["voice"].strip().lower() + + # Get diffusion steps from request or use default + steps = int(request.form.get("steps", 7)) + + if voice not in voices: + error_response = { + "error": "Invalid voice selected. Available voices: " + ", ".join(voicelist) + } + return jsonify(error_response), 400 + + v = voices[voice] + texts = split_and_recombine_text(text) + + def generate(): + is_first_chunk = True + for t in texts: + # Generate audio using the pre-computed voice style + wav = msinference.inference( + t, v, alpha=0.3, beta=0.7, diffusion_steps=steps, embedding_scale=1 + ) + output_buffer = io.BytesIO() + write(output_buffer, 24000, wav) + + # Seek to start and skip WAV header for chunks + output_buffer.seek(0) + if is_first_chunk: + # For first chunk, include WAV header + data = output_buffer.read() + is_first_chunk = False + else: + # For subsequent chunks, skip the 44-byte WAV header + output_buffer.seek(44) + data = output_buffer.read() + yield data + + return Response(generate(), mimetype="audio/x-wav") + + +@app.route("/api/v1/static", methods=["POST"]) +def serve_wav(): + if "text" not in request.form or "voice" not in request.form: + error_response = { + "error": 'Missing required fields. Please include "text" and "voice" in your request.' + } + return jsonify(error_response), 400 + text = request.form["text"].strip() + voice = request.form["voice"].strip().lower() + if voice not in voices: + error_response = {"error": "Invalid voice selected"} + return jsonify(error_response), 400 + texts = split_and_recombine_text(text) + audios = [] + for t in texts: + audios.append( + msinference.inference( + t, + voices[voice], + alpha=0.3, + beta=0.7, + diffusion_steps=7, + embedding_scale=1, + ) + ) + output_buffer = io.BytesIO() + write(output_buffer, 24000, np.concatenate(audios)) + response = Response(output_buffer.getvalue()) + response.headers["Content-Type"] = "audio/wav" + return response + + +if __name__ == "__main__": + app.run("0.0.0.0") \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 00000000..a1040daf --- /dev/null +++ b/app.py @@ -0,0 +1,103 @@ +# Gradio demo of StyleTTS 2 by @fakerybakery +import gradio as gr +import msinference +import ljinference +import torch +import os +from tortoise.utils.text import split_and_recombine_text +import numpy as np +import pickle +theme = gr.themes.Base( + font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif'], +) +voicelist = ['f-us-1', 'f-us-2', 'f-us-3', 'f-us-4', 'm-us-1', 'm-us-2', 'm-us-3', 'm-us-4'] +voices = {} +import phonemizer +global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True) +# todo: cache computed style, load using pickle +# if os.path.exists('voices.pkl'): + # with open('voices.pkl', 'rb') as f: + # voices = pickle.load(f) +# else: +for v in voicelist: + voices[v] = msinference.compute_style(f'voices/{v}.wav') +def synthesize(text, voice, lngsteps, password, progress=gr.Progress()): + if text.strip() == "": + raise gr.Error("You must enter some text") + if lngsteps > 25: + raise gr.Error("Max 25 steps") + if lngsteps < 5: + raise gr.Error("Min 5 steps") + texts = split_and_recombine_text(text) + v = voice.lower() + audios = [] + for t in progress.tqdm(texts): + audios.append(msinference.inference(t, voices[v], alpha=0.3, beta=0.7, diffusion_steps=lngsteps, embedding_scale=1)) + return (24000, np.concatenate(audios)) +def clsynthesize(text, voice, vcsteps): + if text.strip() == "": + raise gr.Error("You must enter some text") + # if global_phonemizer.phonemize([text]) > 300: + if len(text) > 400: + raise gr.Error("Text must be under 400 characters") + return (24000, msinference.inference(text, msinference.compute_style(voice), alpha=0.3, beta=0.7, diffusion_steps=vcsteps, embedding_scale=1)) +def ljsynthesize(text): + if text.strip() == "": + raise gr.Error("You must enter some text") + # if global_phonemizer.phonemize([text]) > 300: + if len(text) > 400: + raise gr.Error("Text must be under 400 characters") + noise = torch.randn(1,1,256).to('cuda' if torch.cuda.is_available() else 'cpu') + return (24000, ljinference.inference(text, noise, diffusion_steps=7, embedding_scale=1)) + + +with gr.Blocks() as vctk: # just realized it isn't vctk but libritts but i'm too lazy to change it rn + with gr.Row(): + with gr.Column(scale=1): + inp = gr.Textbox(label="Text", info="What would you like StyleTTS 2 to read? It works better on full sentences.", interactive=True) + voice = gr.Dropdown(voicelist, label="Voice", info="Select a default voice.", value='m-us-2', interactive=True) + multispeakersteps = gr.Slider(minimum=5, maximum=15, value=7, step=1, label="Diffusion Steps", info="Higher = better quality, but slower", interactive=True) + # use_gruut = gr.Checkbox(label="Use alternate phonemizer (Gruut) - Experimental") + with gr.Column(scale=1): + btn = gr.Button("Synthesize", variant="primary") + audio = gr.Audio(interactive=False, label="Synthesized Audio") + btn.click(synthesize, inputs=[inp, voice, multispeakersteps], outputs=[audio], concurrency_limit=4) +with gr.Blocks() as clone: + with gr.Row(): + with gr.Column(scale=1): + clinp = gr.Textbox(label="Text", info="What would you like StyleTTS 2 to read? It works better on full sentences.", interactive=True) + clvoice = gr.Audio(label="Voice", interactive=True, type='filepath', max_length=300) + vcsteps = gr.Slider(minimum=5, maximum=20, value=20, step=1, label="Diffusion Steps", info="Higher = better quality, but slower", interactive=True) + with gr.Column(scale=1): + clbtn = gr.Button("Synthesize", variant="primary") + claudio = gr.Audio(interactive=False, label="Synthesized Audio") + clbtn.click(clsynthesize, inputs=[clinp, clvoice, vcsteps], outputs=[claudio], concurrency_limit=4) +with gr.Blocks() as lj: + with gr.Row(): + with gr.Column(scale=1): + ljinp = gr.Textbox(label="Text", info="What would you like StyleTTS 2 to read? It works better on full sentences.", interactive=True) + with gr.Column(scale=1): + ljbtn = gr.Button("Synthesize", variant="primary") + ljaudio = gr.Audio(interactive=False, label="Synthesized Audio") + ljbtn.click(ljsynthesize, inputs=[ljinp], outputs=[ljaudio], concurrency_limit=4) +with gr.Blocks(title="StyleTTS 2", css="footer{display:none !important}", theme=theme) as demo: + gr.Markdown("""# StyleTTS 2 + +[Paper](https://arxiv.org/abs/2306.07691) - [Samples](https://styletts2.github.io/) - [Code](https://github.com/yl4579/StyleTTS2) + +GUI of StyleTTS 2 by [mrfakename](https://twitter.com/realmrfakename). + +#### Help the StyleTTS 2 space get to the top of HF Trending! [Give it a Like!](https://huggingface.co/spaces/styletts2/styletts2) + +**Before using this demo, you agree to inform the listeners that the speech samples are synthesized by the pre-trained models, unless you have the permission to use the voice you synthesize. That is, you agree to only use voices whose speakers grant the permission to have their voice cloned, either directly or by license before making synthesized voices public, or you have to publicly announce that these voices are synthesized if you do not have the permission to use these voices.** + +**NOTE: StyleTTS 2 does better on longer texts.** For example, making it say "hi" will produce a lower-quality result than making it say a longer phrase.""") + gr.TabbedInterface([vctk, clone, lj], ['Multi-Voice', 'Voice Cloning', 'LJSpeech']) + gr.Markdown(""" +Demo by [mrfakename](https://twitter.com/realmrfakename). I am not affiliated with the StyleTTS 2 authors. + +This is the local version of the demo +""") +if __name__ == "__main__": + demo.queue(api_open=False, max_size=15).launch(show_api=False) + diff --git a/audio_streamer.py b/audio_streamer.py new file mode 100644 index 00000000..5e7482e5 --- /dev/null +++ b/audio_streamer.py @@ -0,0 +1,111 @@ +""" +Audio streaming utilities for WebSocket TTS. +Handles MP3 encoding and base64 chunking for incremental audio delivery. +""" + +import io +import base64 +import numpy as np +from pydub import AudioSegment +import logging + +logger = logging.getLogger(__name__) + + +class AudioStreamer: + """Streams audio as base64-encoded MP3 chunks.""" + + def __init__(self, sample_rate: int = 24000): + """ + Initialize audio streamer. + + Args: + sample_rate: Audio sample rate in Hz (default 24000) + """ + self.sample_rate = sample_rate + + def create_mp3_bytes(self, audio_data: np.ndarray) -> bytes: + """ + Convert numpy audio array to MP3 bytes. + + Args: + audio_data: Audio waveform as numpy array + + Returns: + MP3 file bytes + """ + # Normalize audio data to 16-bit range + if audio_data.dtype != np.int16: + audio_data = (audio_data * 32767).astype(np.int16) + + # Create AudioSegment from numpy array + audio_segment = AudioSegment( + audio_data.tobytes(), + frame_rate=self.sample_rate, + sample_width=2, # 16-bit + channels=1, # Mono + ) + + # Export to MP3 + buffer = io.BytesIO() + audio_segment.export(buffer, format="mp3", bitrate="128k") + buffer.seek(0) + return buffer.read() + + def encode_audio_chunk(self, audio_data: np.ndarray) -> str: + """ + Encode audio data to base64 MP3 string. + + Args: + audio_data: Audio waveform as numpy array + + Returns: + Base64-encoded MP3 audio string + """ + mp3_bytes = self.create_mp3_bytes(audio_data) + return base64.b64encode(mp3_bytes).decode("utf-8") + + def stream_audio_frames(self, audio_data: np.ndarray, chunk_duration_ms: int = 300): + """ + Generator that yields audio in fixed-duration base64 MP3 chunks. + + Args: + audio_data: Complete audio waveform as numpy array + chunk_duration_ms: Duration of each chunk in milliseconds + + Yields: + Tuples of (base64_audio, is_first_chunk, is_final_chunk) + """ + chunk_samples = int(self.sample_rate * chunk_duration_ms / 1000) + total_samples = len(audio_data) + + if total_samples == 0: + logger.warning("Empty audio data received") + return + + num_chunks = (total_samples + chunk_samples - 1) // chunk_samples + + for i in range(num_chunks): + start_idx = i * chunk_samples + end_idx = min(start_idx + chunk_samples, total_samples) + + chunk = audio_data[start_idx:end_idx] + is_first = i == 0 + is_final = i == num_chunks - 1 + + # Encode chunk as MP3 + base64_audio = self.encode_audio_chunk(chunk) + + yield base64_audio, is_first, is_final + + def encode_full_audio(self, audio_data: np.ndarray) -> str: + """ + Encode complete audio as MP3 to base64. + + Args: + audio_data: Audio waveform as numpy array + + Returns: + Base64-encoded complete MP3 file + """ + return self.encode_audio_chunk(audio_data) diff --git a/inference_manager.py b/inference_manager.py new file mode 100644 index 00000000..b2295a6e --- /dev/null +++ b/inference_manager.py @@ -0,0 +1,160 @@ +""" +GPU-safe inference manager with request queuing and semaphore control. +Handles concurrent TTS requests with low latency and prevents GPU contention. +""" + +import asyncio +import time +import logging +from typing import Optional, List +import numpy as np +import msinference + +logger = logging.getLogger(__name__) + + +class InferenceManager: + """Manages GPU inference with concurrency control and queuing.""" + + def __init__( + self, max_queue_size: int = 100, voice_list: Optional[List[str]] = None + ): + """ + Initialize inference manager. + + Args: + max_queue_size: Maximum number of pending inference requests + voice_list: List of voice IDs to precompute styles for + """ + self.gpu_semaphore = asyncio.Semaphore(1) # Single GPU access at a time + self.max_queue_size = max_queue_size + self.queue_size = 0 + self.total_requests = 0 + self.failed_requests = 0 + self.voices = {} + + # Precompute voice styles + if voice_list: + logger.info("Precomputing %d voice styles...", len(voice_list)) + for voice_id in voice_list: + voice_path = f"voices/{voice_id}.wav" + try: + self.voices[voice_id] = msinference.compute_style(voice_path) + logger.info(" ✓ Loaded voice: %s", voice_id) + except Exception as e: + logger.error(" ✗ Failed to load voice %s: %s", voice_id, str(e)) + + logger.info( + "InferenceManager initialized with max_queue_size=%d, %d voices loaded", + max_queue_size, + len(self.voices), + ) + + async def generate_audio( + self, + text: str, + voice: str, + alpha: float = 0.3, + beta: float = 0.7, + diffusion_steps: int = 7, + embedding_scale: float = 1.0, + ) -> Optional[np.ndarray]: + """ + Generate audio from text using specified voice. + + Args: + text: Input text to synthesize + voice: Voice ID (e.g., 'f-us-1', 'm-us-2') + alpha: Style weight (default 0.3) + beta: Prosody weight (default 0.7) + diffusion_steps: Number of diffusion steps (default 7) + embedding_scale: Style embedding scale (default 1.0) + + Returns: + Audio waveform as numpy array (24kHz sample rate) or None on failure + """ + # Check queue capacity + if self.queue_size >= self.max_queue_size: + logger.warning( + "Queue full, rejecting request (queue_size=%d)", self.queue_size + ) + self.failed_requests += 1 + return None + + self.queue_size += 1 + self.total_requests += 1 + + try: + # Acquire GPU semaphore + async with self.gpu_semaphore: + start_time = time.time() + + # Run inference in thread pool to avoid blocking event loop + loop = asyncio.get_event_loop() + wav = await loop.run_in_executor( + None, + self._inference_sync, + text, + voice, + alpha, + beta, + diffusion_steps, + embedding_scale, + ) + + elapsed = time.time() - start_time + logger.info( + "Generated audio for text='%s...' voice=%s in %.2fs", + text[:30], + voice, + elapsed, + ) + + return wav + + except Exception as e: + logger.error("Inference failed: %s", str(e), exc_info=True) + self.failed_requests += 1 + return None + finally: + self.queue_size -= 1 + + def _inference_sync( + self, + text: str, + voice: str, + alpha: float, + beta: float, + diffusion_steps: int, + embedding_scale: float, + ) -> np.ndarray: + """Synchronous inference call wrapped by async executor.""" + # Get precomputed voice style + if voice not in self.voices: + raise ValueError(f"Voice '{voice}' not found in precomputed voices") + + voice_style = self.voices[voice] + + # Use msinference with precomputed style tensor + wav = msinference.inference( + text, + voice_style, + alpha=alpha, + beta=beta, + diffusion_steps=diffusion_steps, + embedding_scale=embedding_scale, + ) + return wav + + def get_stats(self) -> dict: + """Get current statistics.""" + return { + "queue_size": self.queue_size, + "total_requests": self.total_requests, + "failed_requests": self.failed_requests, + "success_rate": ( + (self.total_requests - self.failed_requests) / self.total_requests + if self.total_requests > 0 + else 1.0 + ), + } diff --git a/ljinference.py b/ljinference.py new file mode 100644 index 00000000..171174bb --- /dev/null +++ b/ljinference.py @@ -0,0 +1,225 @@ +from cached_path import cached_path + + +import torch +torch.manual_seed(0) +torch.backends.cudnn.benchmark = False +torch.backends.cudnn.deterministic = True + +import random +random.seed(0) + +import numpy as np +np.random.seed(0) + +import nltk +nltk.download('punkt') + +# load packages +import time +import random +import yaml +from munch import Munch +import numpy as np +import torch +from torch import nn +import torch.nn.functional as F +import torchaudio +import librosa +from nltk.tokenize import word_tokenize + +from models import * +from utils import * +from text_utils import TextCleaner +textclenaer = TextCleaner() + + +device = 'cuda' if torch.cuda.is_available() else 'cpu' + +to_mel = torchaudio.transforms.MelSpectrogram( + n_mels=80, n_fft=2048, win_length=1200, hop_length=300) +mean, std = -4, 4 + +def length_to_mask(lengths): + mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) + mask = torch.gt(mask+1, lengths.unsqueeze(1)) + return mask + +def preprocess(wave): + wave_tensor = torch.from_numpy(wave).float() + mel_tensor = to_mel(wave_tensor) + mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std + return mel_tensor + +def compute_style(ref_dicts): + reference_embeddings = {} + for key, path in ref_dicts.items(): + wave, sr = librosa.load(path, sr=24000) + audio, index = librosa.effects.trim(wave, top_db=30) + if sr != 24000: + audio = librosa.resample(audio, sr, 24000) + mel_tensor = preprocess(audio).to(device) + + with torch.no_grad(): + ref = model.style_encoder(mel_tensor.unsqueeze(1)) + reference_embeddings[key] = (ref.squeeze(1), audio) + + return reference_embeddings + +# load phonemizer +import phonemizer +global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True, words_mismatch='ignore') + +# phonemizer = Phonemizer.from_checkpoint(str(cached_path('https://public-asai-dl-models.s3.eu-central-1.amazonaws.com/DeepPhonemizer/en_us_cmudict_ipa_forward.pt'))) + + +config = yaml.safe_load(open(str(cached_path('hf://yl4579/StyleTTS2-LJSpeech/Models/LJSpeech/config.yml')))) + +# load pretrained ASR model +ASR_config = config.get('ASR_config', False) +ASR_path = config.get('ASR_path', False) +text_aligner = load_ASR_models(ASR_path, ASR_config) + +# load pretrained F0 model +F0_path = config.get('F0_path', False) +pitch_extractor = load_F0_models(F0_path) + +# load BERT model +from Utils.PLBERT.util import load_plbert +BERT_path = config.get('PLBERT_dir', False) +plbert = load_plbert(BERT_path) + +model = build_model(recursive_munch(config['model_params']), text_aligner, pitch_extractor, plbert) +_ = [model[key].eval() for key in model] +_ = [model[key].to(device) for key in model] + +# params_whole = torch.load("Models/LJSpeech/epoch_2nd_00100.pth", map_location='cpu') +params_whole = torch.load(str(cached_path('hf://yl4579/StyleTTS2-LJSpeech/Models/LJSpeech/epoch_2nd_00100.pth')), map_location='cpu') +params = params_whole['net'] + +for key in model: + if key in params: + print('%s loaded' % key) + try: + model[key].load_state_dict(params[key]) + except: + from collections import OrderedDict + state_dict = params[key] + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + name = k[7:] # remove `module.` + new_state_dict[name] = v + # load params + model[key].load_state_dict(new_state_dict, strict=False) +# except: +# _load(params[key], model[key]) +_ = [model[key].eval() for key in model] + +from Modules.diffusion.sampler import DiffusionSampler, ADPM2Sampler, KarrasSchedule + +sampler = DiffusionSampler( + model.diffusion.diffusion, + sampler=ADPM2Sampler(), + sigma_schedule=KarrasSchedule(sigma_min=0.0001, sigma_max=3.0, rho=9.0), # empirical parameters + clamp=False +) + +def inference(text, noise, diffusion_steps=5, embedding_scale=1): + text = text.strip() + text = text.replace('"', '') + ps = global_phonemizer.phonemize([text]) + ps = word_tokenize(ps[0]) + ps = ' '.join(ps) + + tokens = textclenaer(ps) + tokens.insert(0, 0) + tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) + + with torch.no_grad(): + input_lengths = torch.LongTensor([tokens.shape[-1]]).to(tokens.device) + text_mask = length_to_mask(input_lengths).to(tokens.device) + + t_en = model.text_encoder(tokens, input_lengths, text_mask) + bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) + d_en = model.bert_encoder(bert_dur).transpose(-1, -2) + + s_pred = sampler(noise, + embedding=bert_dur[0].unsqueeze(0), num_steps=diffusion_steps, + embedding_scale=embedding_scale).squeeze(0) + + s = s_pred[:, 128:] + ref = s_pred[:, :128] + + d = model.predictor.text_encoder(d_en, s, input_lengths, text_mask) + + x, _ = model.predictor.lstm(d) + duration = model.predictor.duration_proj(x) + duration = torch.sigmoid(duration).sum(axis=-1) + pred_dur = torch.round(duration.squeeze()).clamp(min=1) + + pred_dur[-1] += 5 + + pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) + c_frame = 0 + for i in range(pred_aln_trg.size(0)): + pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 + c_frame += int(pred_dur[i].data) + + # encode prosody + en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) + F0_pred, N_pred = model.predictor.F0Ntrain(en, s) + out = model.decoder((t_en @ pred_aln_trg.unsqueeze(0).to(device)), + F0_pred, N_pred, ref.squeeze().unsqueeze(0)) + + return out.squeeze().cpu().numpy() + +def LFinference(text, s_prev, noise, alpha=0.7, diffusion_steps=5, embedding_scale=1): + text = text.strip() + text = text.replace('"', '') + ps = global_phonemizer.phonemize([text]) + ps = word_tokenize(ps[0]) + ps = ' '.join(ps) + + tokens = textclenaer(ps) + tokens.insert(0, 0) + tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) + + with torch.no_grad(): + input_lengths = torch.LongTensor([tokens.shape[-1]]).to(tokens.device) + text_mask = length_to_mask(input_lengths).to(tokens.device) + + t_en = model.text_encoder(tokens, input_lengths, text_mask) + bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) + d_en = model.bert_encoder(bert_dur).transpose(-1, -2) + + s_pred = sampler(noise, + embedding=bert_dur[0].unsqueeze(0), num_steps=diffusion_steps, + embedding_scale=embedding_scale).squeeze(0) + + if s_prev is not None: + # convex combination of previous and current style + s_pred = alpha * s_prev + (1 - alpha) * s_pred + + s = s_pred[:, 128:] + ref = s_pred[:, :128] + + d = model.predictor.text_encoder(d_en, s, input_lengths, text_mask) + + x, _ = model.predictor.lstm(d) + duration = model.predictor.duration_proj(x) + duration = torch.sigmoid(duration).sum(axis=-1) + pred_dur = torch.round(duration.squeeze()).clamp(min=1) + + pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) + c_frame = 0 + for i in range(pred_aln_trg.size(0)): + pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 + c_frame += int(pred_dur[i].data) + + # encode prosody + en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) + F0_pred, N_pred = model.predictor.F0Ntrain(en, s) + out = model.decoder((t_en @ pred_aln_trg.unsqueeze(0).to(device)), + F0_pred, N_pred, ref.squeeze().unsqueeze(0)) + + return out.squeeze().cpu().numpy(), s_pred \ No newline at end of file diff --git a/models.py b/models.py index 84bbb03d..36a5c6ec 100644 --- a/models.py +++ b/models.py @@ -585,7 +585,7 @@ def load_F0_models(path): # load F0 model F0_model = JDCNet(num_class=1, seq_len=192) - params = torch.load(path, map_location='cpu')['net'] + params = torch.load(path, map_location='cpu', weights_only=False)['net'] F0_model.load_state_dict(params) _ = F0_model.train() @@ -601,7 +601,7 @@ def _load_config(path): def _load_model(model_config, model_path): model = ASRCNN(**model_config) - params = torch.load(model_path, map_location='cpu')['model'] + params = torch.load(model_path, map_location='cpu', weights_only=False)['model'] model.load_state_dict(params) return model @@ -694,7 +694,7 @@ def build_model(args, text_aligner, pitch_extractor, bert): return nets def load_checkpoint(model, optimizer, path, load_only_params=True, ignore_modules=[]): - state = torch.load(path, map_location='cpu') + state = torch.load(path, map_location='cpu', weights_only=False) params = state['net'] for key in model: if key in params and key not in ignore_modules: diff --git a/msinference.py b/msinference.py new file mode 100644 index 00000000..0f9d6e5b --- /dev/null +++ b/msinference.py @@ -0,0 +1,356 @@ +from cached_path import cached_path +import nltk +nltk.download('punkt') +from scipy.io.wavfile import write +import torch +torch.manual_seed(0) +torch.backends.cudnn.benchmark = False +torch.backends.cudnn.deterministic = True + +import random +random.seed(0) + +import numpy as np +np.random.seed(0) + +# load packages +import time +import random +import yaml +from munch import Munch +import numpy as np +import torch +from torch import nn +import torch.nn.functional as F +import torchaudio +import librosa +from nltk.tokenize import word_tokenize + +from models import * +from utils import * +from text_utils import TextCleaner +textclenaer = TextCleaner() + + +to_mel = torchaudio.transforms.MelSpectrogram( + n_mels=80, n_fft=2048, win_length=1200, hop_length=300) +mean, std = -4, 4 + +def length_to_mask(lengths): + mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) + mask = torch.gt(mask+1, lengths.unsqueeze(1)) + return mask + +def preprocess(wave): + wave_tensor = torch.from_numpy(wave).float() + mel_tensor = to_mel(wave_tensor) + mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std + return mel_tensor + +def compute_style(path): + wave, sr = librosa.load(path, sr=24000) + audio, index = librosa.effects.trim(wave, top_db=30) + if sr != 24000: + audio = librosa.resample(audio, sr, 24000) + mel_tensor = preprocess(audio).to(device) + + with torch.no_grad(): + ref_s = model.style_encoder(mel_tensor.unsqueeze(1)) + ref_p = model.predictor_encoder(mel_tensor.unsqueeze(1)) + + return torch.cat([ref_s, ref_p], dim=1) + +device = 'cpu' +if torch.cuda.is_available(): + device = 'cuda' +elif torch.backends.mps.is_available(): + # print("MPS would be available but cannot be used rn") + pass + # device = 'mps' + +import phonemizer +global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True) +# phonemizer = Phonemizer.from_checkpoint(str(cached_path('https://public-asai-dl-models.s3.eu-central-1.amazonaws.com/DeepPhonemizer/en_us_cmudict_ipa_forward.pt'))) + + +# config = yaml.safe_load(open("Models/LibriTTS/config.yml")) +config = yaml.safe_load(open(str(cached_path("hf://yl4579/StyleTTS2-LibriTTS/Models/LibriTTS/config.yml")))) + +# load pretrained ASR model +ASR_config = config.get('ASR_config', False) +ASR_path = config.get('ASR_path', False) +text_aligner = load_ASR_models(ASR_path, ASR_config) + +# load pretrained F0 model +F0_path = config.get('F0_path', False) +pitch_extractor = load_F0_models(F0_path) + +# load BERT model +from Utils.PLBERT.util import load_plbert +BERT_path = config.get('PLBERT_dir', False) +plbert = load_plbert(BERT_path) + +model_params = recursive_munch(config['model_params']) +model = build_model(model_params, text_aligner, pitch_extractor, plbert) +_ = [model[key].eval() for key in model] +_ = [model[key].to(device) for key in model] + +# params_whole = torch.load("Models/LibriTTS/epochs_2nd_00020.pth", map_location='cpu') +params_whole = torch.load(str(cached_path("hf://yl4579/StyleTTS2-LibriTTS/Models/LibriTTS/epochs_2nd_00020.pth")), map_location='cpu') +params = params_whole['net'] + +for key in model: + if key in params: + print('%s loaded' % key) + try: + model[key].load_state_dict(params[key]) + except: + from collections import OrderedDict + state_dict = params[key] + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + name = k[7:] # remove `module.` + new_state_dict[name] = v + # load params + model[key].load_state_dict(new_state_dict, strict=False) +# except: +# _load(params[key], model[key]) +_ = [model[key].eval() for key in model] + +from Modules.diffusion.sampler import DiffusionSampler, ADPM2Sampler, KarrasSchedule + +sampler = DiffusionSampler( + model.diffusion.diffusion, + sampler=ADPM2Sampler(), + sigma_schedule=KarrasSchedule(sigma_min=0.0001, sigma_max=3.0, rho=9.0), # empirical parameters + clamp=False +) + +def inference(text, ref_s, alpha = 0.3, beta = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False): + text = text.strip() + ps = global_phonemizer.phonemize([text]) + ps = word_tokenize(ps[0]) + ps = ' '.join(ps) + tokens = textclenaer(ps) + tokens.insert(0, 0) + tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) + + with torch.no_grad(): + input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device) + text_mask = length_to_mask(input_lengths).to(device) + + t_en = model.text_encoder(tokens, input_lengths, text_mask) + bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) + d_en = model.bert_encoder(bert_dur).transpose(-1, -2) + + s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device), + embedding=bert_dur, + embedding_scale=embedding_scale, + features=ref_s, # reference from the same speaker as the embedding + num_steps=diffusion_steps).squeeze(1) + + + s = s_pred[:, 128:] + ref = s_pred[:, :128] + + ref = alpha * ref + (1 - alpha) * ref_s[:, :128] + s = beta * s + (1 - beta) * ref_s[:, 128:] + + d = model.predictor.text_encoder(d_en, + s, input_lengths, text_mask) + + x, _ = model.predictor.lstm(d) + duration = model.predictor.duration_proj(x) + + duration = torch.sigmoid(duration).sum(axis=-1) + pred_dur = torch.round(duration.squeeze()).clamp(min=1) + + + pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) + c_frame = 0 + for i in range(pred_aln_trg.size(0)): + pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 + c_frame += int(pred_dur[i].data) + + # encode prosody + en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) + if model_params.decoder.type == "hifigan": + asr_new = torch.zeros_like(en) + asr_new[:, :, 0] = en[:, :, 0] + asr_new[:, :, 1:] = en[:, :, 0:-1] + en = asr_new + + F0_pred, N_pred = model.predictor.F0Ntrain(en, s) + + asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device)) + if model_params.decoder.type == "hifigan": + asr_new = torch.zeros_like(asr) + asr_new[:, :, 0] = asr[:, :, 0] + asr_new[:, :, 1:] = asr[:, :, 0:-1] + asr = asr_new + + out = model.decoder(asr, + F0_pred, N_pred, ref.squeeze().unsqueeze(0)) + + + return out.squeeze().cpu().numpy()[..., :-50] # weird pulse at the end of the model, need to be fixed later + +def LFinference(text, s_prev, ref_s, alpha = 0.3, beta = 0.7, t = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False): + text = text.strip() + ps = global_phonemizer.phonemize([text]) + ps = word_tokenize(ps[0]) + ps = ' '.join(ps) + ps = ps.replace('``', '"') + ps = ps.replace("''", '"') + + tokens = textclenaer(ps) + tokens.insert(0, 0) + tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) + + with torch.no_grad(): + input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device) + text_mask = length_to_mask(input_lengths).to(device) + + t_en = model.text_encoder(tokens, input_lengths, text_mask) + bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) + d_en = model.bert_encoder(bert_dur).transpose(-1, -2) + + s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device), + embedding=bert_dur, + embedding_scale=embedding_scale, + features=ref_s, # reference from the same speaker as the embedding + num_steps=diffusion_steps).squeeze(1) + + if s_prev is not None: + # convex combination of previous and current style + s_pred = t * s_prev + (1 - t) * s_pred + + s = s_pred[:, 128:] + ref = s_pred[:, :128] + + ref = alpha * ref + (1 - alpha) * ref_s[:, :128] + s = beta * s + (1 - beta) * ref_s[:, 128:] + + s_pred = torch.cat([ref, s], dim=-1) + + d = model.predictor.text_encoder(d_en, + s, input_lengths, text_mask) + + x, _ = model.predictor.lstm(d) + duration = model.predictor.duration_proj(x) + + duration = torch.sigmoid(duration).sum(axis=-1) + pred_dur = torch.round(duration.squeeze()).clamp(min=1) + + + pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) + c_frame = 0 + for i in range(pred_aln_trg.size(0)): + pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 + c_frame += int(pred_dur[i].data) + + # encode prosody + en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) + if model_params.decoder.type == "hifigan": + asr_new = torch.zeros_like(en) + asr_new[:, :, 0] = en[:, :, 0] + asr_new[:, :, 1:] = en[:, :, 0:-1] + en = asr_new + + F0_pred, N_pred = model.predictor.F0Ntrain(en, s) + + asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device)) + if model_params.decoder.type == "hifigan": + asr_new = torch.zeros_like(asr) + asr_new[:, :, 0] = asr[:, :, 0] + asr_new[:, :, 1:] = asr[:, :, 0:-1] + asr = asr_new + + out = model.decoder(asr, + F0_pred, N_pred, ref.squeeze().unsqueeze(0)) + + + return out.squeeze().cpu().numpy()[..., :-100], s_pred # weird pulse at the end of the model, need to be fixed later + +def STinference(text, ref_s, ref_text, alpha = 0.3, beta = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False): + text = text.strip() + ps = global_phonemizer.phonemize([text]) + ps = word_tokenize(ps[0]) + ps = ' '.join(ps) + + tokens = textclenaer(ps) + tokens.insert(0, 0) + tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) + + ref_text = ref_text.strip() + ps = global_phonemizer.phonemize([ref_text]) + ps = word_tokenize(ps[0]) + ps = ' '.join(ps) + + ref_tokens = textclenaer(ps) + ref_tokens.insert(0, 0) + ref_tokens = torch.LongTensor(ref_tokens).to(device).unsqueeze(0) + + + with torch.no_grad(): + input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device) + text_mask = length_to_mask(input_lengths).to(device) + + t_en = model.text_encoder(tokens, input_lengths, text_mask) + bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) + d_en = model.bert_encoder(bert_dur).transpose(-1, -2) + + ref_input_lengths = torch.LongTensor([ref_tokens.shape[-1]]).to(device) + ref_text_mask = length_to_mask(ref_input_lengths).to(device) + ref_bert_dur = model.bert(ref_tokens, attention_mask=(~ref_text_mask).int()) + s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device), + embedding=bert_dur, + embedding_scale=embedding_scale, + features=ref_s, # reference from the same speaker as the embedding + num_steps=diffusion_steps).squeeze(1) + + + s = s_pred[:, 128:] + ref = s_pred[:, :128] + + ref = alpha * ref + (1 - alpha) * ref_s[:, :128] + s = beta * s + (1 - beta) * ref_s[:, 128:] + + d = model.predictor.text_encoder(d_en, + s, input_lengths, text_mask) + + x, _ = model.predictor.lstm(d) + duration = model.predictor.duration_proj(x) + + duration = torch.sigmoid(duration).sum(axis=-1) + pred_dur = torch.round(duration.squeeze()).clamp(min=1) + + + pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) + c_frame = 0 + for i in range(pred_aln_trg.size(0)): + pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 + c_frame += int(pred_dur[i].data) + + # encode prosody + en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) + if model_params.decoder.type == "hifigan": + asr_new = torch.zeros_like(en) + asr_new[:, :, 0] = en[:, :, 0] + asr_new[:, :, 1:] = en[:, :, 0:-1] + en = asr_new + + F0_pred, N_pred = model.predictor.F0Ntrain(en, s) + + asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device)) + if model_params.decoder.type == "hifigan": + asr_new = torch.zeros_like(asr) + asr_new[:, :, 0] = asr[:, :, 0] + asr_new[:, :, 1:] = asr[:, :, 0:-1] + asr = asr_new + + out = model.decoder(asr, + F0_pred, N_pred, ref.squeeze().unsqueeze(0)) + + + return out.squeeze().cpu().numpy()[..., :-50] # weird pulse at the end of the model, need to be fixed later \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 8b8d1122..30bb8d26 100644 --- a/requirements.txt +++ b/requirements.txt @@ -14,4 +14,14 @@ einops-exts tqdm typing typing-extensions -git+https://github.com/resemble-ai/monotonic_align.git \ No newline at end of file +git+https://github.com/resemble-ai/monotonic_align.git # or resemble-monotonic-align +gradio +phonemizer +cached-path +tortoise-tts # for the Gradio demo, splitting text +flask # for api +markdown # for api +flask-cors +fastapi # for WebSocket API +uvicorn[standard] # ASGI server for WebSocket +websockets # WebSocket support \ No newline at end of file diff --git a/test_api_client.py b/test_api_client.py new file mode 100644 index 00000000..b2bf7b0f --- /dev/null +++ b/test_api_client.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +""" +StyleTTS2 Streaming API Client +This script demonstrates how to use the StyleTTS2 streaming API endpoint. +""" + +import requests +import sys +from pathlib import Path +import argparse + + +class StyleTTS2Client: + """Client for interacting with StyleTTS2 Streaming API""" + + def __init__(self, base_url="http://localhost:5000"): + """ + Initialize the client + + Args: + base_url (str): Base URL of the API server + """ + self.base_url = base_url.rstrip("/") + self.stream_endpoint = f"{self.base_url}/api/v1/stream" + + # Available voices + self.available_voices = [ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", + ] + + def check_server(self): + """Check if the API server is running""" + try: + response = requests.get(self.base_url, timeout=5) + if response.status_code == 200: + print(f"✓ API server is running at {self.base_url}") + return True + else: + print(f"✗ API server returned status code: {response.status_code}") + return False + except requests.exceptions.ConnectionError: + print(f"✗ Cannot connect to API server at {self.base_url}") + print(" Make sure the server is running with: python api.py") + return False + except Exception as e: + print(f"✗ Error checking server: {e}") + return False + + def synthesize_stream(self, text, voice, output_file, steps=7): + """ + Synthesize speech using the streaming endpoint + + Args: + text (str): Text to synthesize + voice (str): Voice ID to use + output_file (str): Path to save the output WAV file + steps (int): Number of diffusion steps (default: 7, higher=better quality but slower) + + Returns: + bool: True if successful, False otherwise + """ + if voice not in self.available_voices: + print(f"✗ Invalid voice '{voice}'") + print(f" Available voices: {', '.join(self.available_voices)}") + return False + + print(f"\n{'=' * 60}") + print("Synthesizing with streaming API") + print(f"{'=' * 60}") + print(f"Text: {text[:100]}{'...' if len(text) > 100 else ''}") + print(f"Voice: {voice}") + print(f"Diffusion steps: {steps}") + print(f"Output: {output_file}") + print(f"{'=' * 60}\n") + + # Prepare the request + data = {"text": text, "voice": voice, "steps": str(steps)} + + try: + # Make streaming request + print("Sending request to API...") + response = requests.post( + self.stream_endpoint, + data=data, + stream=True, + timeout=300, # 5 minutes timeout + ) + + if response.status_code != 200: + print(f"✗ API returned error status: {response.status_code}") + try: + error_data = response.json() + print(f" Error: {error_data.get('error', 'Unknown error')}") + except Exception: + print(f" Response: {response.text[:200]}") + return False + + # Create output directory if it doesn't exist + output_path = Path(output_file) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Stream the audio data to file + print("Receiving audio stream...") + chunk_count = 0 + total_bytes = 0 + + with open(output_file, "wb") as f: + for chunk in response.iter_content(chunk_size=8192): + if chunk: + f.write(chunk) + chunk_count += 1 + total_bytes += len(chunk) + + # Print progress every 10 chunks + if chunk_count % 10 == 0: + print( + f" Received {chunk_count} chunks ({total_bytes:,} bytes)...", + end="\r", + ) + + print("\n\n✓ Audio saved successfully!") + print(f" File: {output_file}") + print(f" Size: {total_bytes:,} bytes ({total_bytes / 1024:.2f} KB)") + print(f" Chunks received: {chunk_count}") + + return True + + except requests.exceptions.Timeout: + print( + "✗ Request timed out. The text might be too long or the server is slow." + ) + return False + except requests.exceptions.ConnectionError: + print("✗ Connection error. Make sure the API server is running.") + return False + except Exception as e: + print(f"✗ Error during synthesis: {e}") + import traceback + + traceback.print_exc() + return False + + def list_voices(self): + """List all available voices""" + print("\nAvailable Voices:") + print("=" * 40) + for i, voice in enumerate(self.available_voices, 1): + voice_type = "Female" if voice.startswith("f-") else "Male" + print(f"{i}. {voice:10s} - {voice_type} US English") + print("=" * 40) + + +def main(): + parser = argparse.ArgumentParser( + description="StyleTTS2 Streaming API Client", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Simple synthesis + python test_api_client.py -t "Hello world" -v f-us-1 -o output.wav + + # With custom diffusion steps for better quality + python test_api_client.py -t "Hello world" -v m-us-2 -o output.wav -s 10 + + # Long text synthesis + python test_api_client.py -t "This is a longer text..." -v f-us-3 -o long.wav + + # List available voices + python test_api_client.py --list-voices + + # Custom server URL + python test_api_client.py -t "Hello" -v f-us-1 -o out.wav --url http://192.168.1.100:5000 + """, + ) + + parser.add_argument("-t", "--text", type=str, help="Text to synthesize") + parser.add_argument( + "-v", "--voice", type=str, help="Voice ID (e.g., f-us-1, m-us-2)" + ) + parser.add_argument("-o", "--output", type=str, help="Output WAV file path") + parser.add_argument( + "-s", + "--steps", + type=int, + default=7, + help="Diffusion steps (default: 7, higher=better quality)", + ) + parser.add_argument( + "--url", + type=str, + default="http://localhost:5000", + help="API server URL (default: http://localhost:5000)", + ) + parser.add_argument( + "--list-voices", action="store_true", help="List available voices and exit" + ) + parser.add_argument( + "--check-server", + action="store_true", + help="Check if server is running and exit", + ) + + args = parser.parse_args() + + # Initialize client + client = StyleTTS2Client(base_url=args.url) + + # Handle list voices + if args.list_voices: + client.list_voices() + return 0 + + # Handle check server + if args.check_server: + if client.check_server(): + return 0 + else: + return 1 + + # Validate required arguments + if not args.text or not args.voice or not args.output: + parser.print_help() + print("\n✗ Error: --text, --voice, and --output are required for synthesis") + print("\nQuick start:") + print(' python test_api_client.py -t "Hello world" -v f-us-1 -o output.wav') + return 1 + + # Check server before synthesis + if not client.check_server(): + return 1 + + # Perform synthesis + success = client.synthesize_stream( + text=args.text, voice=args.voice, output_file=args.output, steps=args.steps + ) + + if success: + print("\n✓ Synthesis completed successfully!") + print("\nYou can play the audio with:") + print(f" ffplay {args.output}") + print(" or") + print(f" aplay {args.output}") + return 0 + else: + print("\n✗ Synthesis failed") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test_ws_client.py b/test_ws_client.py new file mode 100644 index 00000000..d54326ad --- /dev/null +++ b/test_ws_client.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +""" +WebSocket TTS client for testing StyleTTS2 WebSocket API. +""" + +import asyncio +import json +import base64 +import sys +import argparse +import websockets +from pathlib import Path + + +async def test_websocket_tts( + uri: str, text: str, voice: str = "m-us-1", output_file: str = "output.mp3" +): + """ + Test WebSocket TTS endpoint. + + Args: + uri: WebSocket URI (e.g., ws://localhost:8765/ws/tts) + text: Text to synthesize + voice: Voice ID + output_file: Output MP3 file path + """ + print(f"Connecting to {uri}...") + + audio_chunks = [] + + async with websockets.connect(uri) as websocket: + # Receive welcome message + welcome = await websocket.recv() + print(f"Server: {welcome}") + + # Send text with flush + message = {"text": text, "voice": voice, "flush": True} + + print(f"\nSending: {text[:50]}...") + print(f"Voice: {voice}") + + await websocket.send(json.dumps(message)) + + # Receive audio chunks + chunk_count = 0 + while True: + response = await websocket.recv() + data = json.loads(response) + + if "error" in data: + print(f"Error: {data['error']}") + break + + if "audio" in data and data["audio"]: + audio_chunks.append(data["audio"]) + chunk_count += 1 + print( + f"Received chunk {chunk_count} (isFinal: {data.get('isFinal', False)})" + ) + + if data.get("isFinal"): + print(f"\nReceived {chunk_count} audio chunks") + break + + # Combine and save audio + if audio_chunks: + print(f"Saving audio to {output_file}...") + + # Decode all chunks + audio_bytes = b"".join(base64.b64decode(chunk) for chunk in audio_chunks) + + # Write to file + with open(output_file, "wb") as f: + f.write(audio_bytes) + + print(f"✓ Saved {len(audio_bytes)} bytes to {output_file}") + else: + print("No audio received") + + +async def test_chunked_streaming( + uri: str, text_chunks: list, voice: str = "m-us-1", output_file: str = "output.mp3" +): + """ + Test chunked text streaming (simulates real-time text input). + + Args: + uri: WebSocket URI + text_chunks: List of text chunks to send + voice: Voice ID + output_file: Output MP3 file path + """ + print(f"Connecting to {uri}...") + + audio_chunks = [] + + async with websockets.connect(uri) as websocket: + # Receive welcome message + welcome = await websocket.recv() + print(f"Server: {welcome}") + + # Send text chunks incrementally + for i, chunk in enumerate(text_chunks): + is_last = i == len(text_chunks) - 1 + + message = { + "text": chunk, + "voice": voice, + "flush": is_last, # Only flush on last chunk + } + + print(f"\nSending chunk {i + 1}/{len(text_chunks)}: {chunk[:30]}...") + await websocket.send(json.dumps(message)) + + # Small delay to simulate real-time input + if not is_last: + await asyncio.sleep(0.1) + + # Receive audio + chunk_count = 0 + while True: + response = await websocket.recv() + data = json.loads(response) + + if "error" in data: + print(f"Error: {data['error']}") + break + + if "audio" in data and data["audio"]: + audio_chunks.append(data["audio"]) + chunk_count += 1 + print(f"Received audio chunk {chunk_count}") + + if data.get("isFinal"): + print(f"\nReceived {chunk_count} total audio chunks") + break + + # Save audio + if audio_chunks: + audio_bytes = b"".join(base64.b64decode(chunk) for chunk in audio_chunks) + with open(output_file, "wb") as f: + f.write(audio_bytes) + print(f"✓ Saved to {output_file}") + + +def main(): + parser = argparse.ArgumentParser(description="WebSocket TTS Client") + parser.add_argument( + "--uri", + default="ws://localhost:8765/ws/tts", + help="WebSocket URI (default: ws://localhost:8765/ws/tts)", + ) + parser.add_argument( + "--text", + default="Hello, this is a test of the WebSocket TTS streaming service.", + help="Text to synthesize", + ) + parser.add_argument( + "--voice", + default="m-us-1", + choices=[ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", + ], + help="Voice ID", + ) + parser.add_argument("--output", default="output.mp3", help="Output MP3 file") + parser.add_argument( + "--chunked", action="store_true", help="Test chunked streaming mode" + ) + + args = parser.parse_args() + + try: + if args.chunked: + # Split text into chunks for testing + words = args.text.split() + chunks = [" ".join(words[i : i + 3]) for i in range(0, len(words), 3)] + print(f"Testing chunked mode with {len(chunks)} chunks") + asyncio.run( + test_chunked_streaming(args.uri, chunks, args.voice, args.output) + ) + else: + asyncio.run( + test_websocket_tts(args.uri, args.text, args.voice, args.output) + ) + except KeyboardInterrupt: + print("\nInterrupted") + except Exception as e: + print(f"Error: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/voices/f-us-1.wav b/voices/f-us-1.wav new file mode 100644 index 00000000..557bcd38 Binary files /dev/null and b/voices/f-us-1.wav differ diff --git a/voices/f-us-2.wav b/voices/f-us-2.wav new file mode 100644 index 00000000..6c446ec6 Binary files /dev/null and b/voices/f-us-2.wav differ diff --git a/voices/f-us-3.wav b/voices/f-us-3.wav new file mode 100644 index 00000000..3da63db8 Binary files /dev/null and b/voices/f-us-3.wav differ diff --git a/voices/f-us-4.wav b/voices/f-us-4.wav new file mode 100644 index 00000000..03882013 Binary files /dev/null and b/voices/f-us-4.wav differ diff --git a/voices/m-us-1.wav b/voices/m-us-1.wav new file mode 100644 index 00000000..1e63b4b4 Binary files /dev/null and b/voices/m-us-1.wav differ diff --git a/voices/m-us-2.wav b/voices/m-us-2.wav new file mode 100644 index 00000000..a874bbdb Binary files /dev/null and b/voices/m-us-2.wav differ diff --git a/voices/m-us-3.wav b/voices/m-us-3.wav new file mode 100644 index 00000000..4024dd3b Binary files /dev/null and b/voices/m-us-3.wav differ diff --git a/voices/m-us-4.wav b/voices/m-us-4.wav new file mode 100644 index 00000000..43771b7a Binary files /dev/null and b/voices/m-us-4.wav differ diff --git a/ws_server.py b/ws_server.py new file mode 100644 index 00000000..34f0e188 --- /dev/null +++ b/ws_server.py @@ -0,0 +1,344 @@ +""" +Production-grade WebSocket TTS server with FastAPI. +Handles chunked text input and streams base64 audio output. +""" + +import asyncio +import json +import logging +import time +from contextlib import asynccontextmanager +from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from tortoise.utils.text import split_and_recombine_text +import uvicorn + +from inference_manager import InferenceManager +from audio_streamer import AudioStreamer + +# Configure logging +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger(__name__) + +# Global instances +inference_manager = None +audio_streamer = AudioStreamer(sample_rate=24000) + +# Available voices +AVAILABLE_VOICES = [ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", +] + +# Server state +server_ready = False + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Lifespan event handler for startup and shutdown.""" + global server_ready, inference_manager + logger.info("Starting StyleTTS2 WebSocket server...") + + # Download NLTK data if needed + import nltk + + try: + nltk.data.find("tokenizers/punkt_tab") + except LookupError: + logger.info("Downloading NLTK punkt_tab...") + nltk.download("punkt_tab", quiet=True) + + # Initialize inference manager with precomputed voices + logger.info("Precomputing voice styles...") + inference_manager = InferenceManager( + max_queue_size=100, voice_list=AVAILABLE_VOICES + ) + logger.info("Models loaded and voices precomputed") + + server_ready = True + logger.info("Server ready to accept WebSocket connections") + + yield + + # Cleanup on shutdown + logger.info("Shutting down server...") + + +# Initialize FastAPI app with lifespan +app = FastAPI( + title="StyleTTS2 WebSocket API", + description="Production TTS streaming service with WebSocket support", + version="1.0.0", + lifespan=lifespan, +) + +# CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +@app.get("/health") +async def health_check(): + """Health check endpoint.""" + if not server_ready: + raise HTTPException(status_code=503, detail="Server initializing") + + stats = inference_manager.get_stats() + return {"status": "healthy", "ready": server_ready, "stats": stats} + + +@app.get("/voices") +async def list_voices(): + """List available voices.""" + return {"voices": AVAILABLE_VOICES} + + +class ConnectionManager: + """Manages WebSocket connection state and text buffering.""" + + def __init__(self, websocket: WebSocket, connection_id: str): + self.websocket = websocket + self.connection_id = connection_id + self.text_buffer = [] + self.voice = "f-us-1" # Default voice + self.last_activity = time.time() + self.active = True + + async def send_json(self, data: dict): + """Send JSON message to client.""" + if not self.active: + return + try: + await self.websocket.send_json(data) + self.last_activity = time.time() + except Exception as e: + logger.debug(f"Failed to send message (connection likely closed): {e}") + self.active = False + + async def send_error(self, error_message: str): + """Send error message to client.""" + if self.active: + await self.send_json({"error": error_message, "isFinal": True}) + + def add_text(self, text: str): + """Add text chunk to buffer.""" + if text: + self.text_buffer.append(text) + self.last_activity = time.time() + + def get_buffered_text(self) -> str: + """Get and clear text buffer.""" + text = " ".join(self.text_buffer) + self.text_buffer = [] + return text + + def is_idle(self, timeout_seconds: int = 120) -> bool: + """Check if connection has been idle for too long.""" + return (time.time() - self.last_activity) > timeout_seconds + + +@app.websocket("/ws/tts") +async def websocket_tts_endpoint(websocket: WebSocket): + """ + WebSocket endpoint for TTS streaming. + + Expected input JSON: + { + "text": "chunk of text", + "voice": "f-us-1", # optional, defaults to f-us-1 + "flush": true/false # if true, generate audio from buffered text + } + + Output JSON: + { + "audio": "base64_encoded_audio_bytes", + "isFinal": true/false + } + """ + await websocket.accept() + + connection_id = f"{websocket.client.host}:{websocket.client.port}" + conn_manager = ConnectionManager(websocket, connection_id) + + logger.info(f"WebSocket connected: {connection_id}") + + # Send welcome message + await conn_manager.send_json( + { + "status": "connected", + "available_voices": AVAILABLE_VOICES, + "message": "Send text chunks with 'flush: true' to generate audio", + } + ) + + try: + # Start idle timeout monitor + timeout_task = asyncio.create_task(monitor_idle_timeout(conn_manager)) + + while conn_manager.active: + try: + # Receive message with timeout + data = await asyncio.wait_for(websocket.receive_json(), timeout=5.0) + + # Parse message + text = data.get("text", "").strip() + voice = data.get("voice", conn_manager.voice).lower() + flush = data.get("flush", False) + + # Validate voice + if voice not in AVAILABLE_VOICES: + await conn_manager.send_error( + f"Invalid voice '{voice}'. Available: {AVAILABLE_VOICES}" + ) + continue + + conn_manager.voice = voice + + # Add text to buffer + if text: + conn_manager.add_text(text) + + # Generate audio if flush is requested + if flush: + buffered_text = conn_manager.get_buffered_text() + + if not buffered_text: + await conn_manager.send_json({"audio": "", "isFinal": True}) + continue + + # Split long text into manageable chunks + text_chunks = split_and_recombine_text(buffered_text) + + logger.info( + f"Processing {len(text_chunks)} text chunks for {connection_id}, " + f"voice={voice}" + ) + + # Process each text chunk + for chunk_idx, text_chunk in enumerate(text_chunks): + is_last_text_chunk = chunk_idx == len(text_chunks) - 1 + + # Generate audio + audio_wav = await inference_manager.generate_audio( + text=text_chunk, + voice=voice, + alpha=0.3, + beta=0.7, + diffusion_steps=7, + embedding_scale=1.0, + ) + + if audio_wav is None: + await conn_manager.send_error( + "Audio generation failed or queue full" + ) + break + + # Send complete audio as single base64-encoded WAV + base64_audio = audio_streamer.encode_full_audio(audio_wav) + await conn_manager.send_json( + { + "audio": base64_audio, + "isFinal": is_last_text_chunk, + } + ) + + logger.info( + f"Sent complete audio for chunk {chunk_idx + 1}/{len(text_chunks)}" + ) + + except asyncio.TimeoutError: + # No message received, continue loop + continue + + except WebSocketDisconnect as e: + # Client disconnected gracefully + logger.info(f"Client disconnected: {connection_id} (code: {e.code})") + break + + except json.JSONDecodeError: + await conn_manager.send_error("Invalid JSON format") + + except Exception as e: + logger.error(f"Error processing message: {e}", exc_info=True) + await conn_manager.send_error(f"Processing error: {str(e)}") + + # Cancel timeout monitor + timeout_task.cancel() + + except WebSocketDisconnect as e: + logger.info(f"WebSocket disconnected: {connection_id} (code: {e.code})") + except Exception as e: + logger.error(f"WebSocket error: {e}", exc_info=True) + finally: + if conn_manager.active: + conn_manager.active = False + logger.info(f"Connection closed: {connection_id}") + + +async def monitor_idle_timeout( + conn_manager: ConnectionManager, timeout_seconds: int = 120 +): + """Monitor connection for idle timeout (default 2 minutes).""" + try: + while conn_manager.active: + await asyncio.sleep(30) # Check every 30 seconds + + if conn_manager.is_idle(timeout_seconds): + logger.warning( + f"Connection {conn_manager.connection_id} idle for {timeout_seconds}s, closing" + ) + await conn_manager.send_json( + { + "status": "timeout", + "message": f"Connection idle for {timeout_seconds} seconds", + "isFinal": True, + } + ) + conn_manager.active = False + await conn_manager.websocket.close() + break + except asyncio.CancelledError: + pass + + +def main(): + """Run the WebSocket server.""" + import sys + + # Parse arguments + host = "0.0.0.0" + port = 8765 + + if len(sys.argv) > 1: + port = int(sys.argv[1]) + + logger.info(f"Starting server on {host}:{port}") + + uvicorn.run( + app, + host=host, + port=port, + log_level="info", + access_log=True, + ws_ping_interval=20, + ws_ping_timeout=20, + ) + + +if __name__ == "__main__": + main()