repo_id
stringlengths
18
103
file_path
stringlengths
30
136
content
stringlengths
2
3.36M
__index_level_0__
int64
0
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/pdt/getters.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_EXTENSIONS_PDT_GETTERS_H_ #define FST_EXTENSIONS_PDT_GETTERS_H_ #include <string> #include <fst/extensions/pdt/compose.h> #include <fst/extensions/pdt/replace.h> namespace fst { namespace script { bool GetPdtComposeFilter(const string &str, PdtComposeFilter *cf); bool GetPdtParserType(const string &str, PdtParserType *pt); } // namespace script } // namespace fst #endif // FST_EXTENSIONS_PDT_GETTERS_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/host-build-dbg.sh
#!/bin/bash set -xe runtime=$1 source $(dirname "$0")/tc-tests-utils.sh source $(dirname "$0")/tf_tc-vars.sh BAZEL_TARGETS=" //native_client:libstt.so " if [ "${runtime}" = "tflite" ]; then BAZEL_BUILD_TFLITE="--define=runtime=tflite" fi; BAZEL_BUILD_FLAGS="${BAZEL_BUILD_TFLITE} ${BAZEL_OPT_FLAGS} ${BAZEL_EXTRA_FLAGS}" BAZEL_ENV_FLAGS="TF_NEED_CUDA=0" SYSTEM_TARGET=host do_bazel_build "dbg" export EXTRA_LOCAL_CFLAGS="-ggdb" do_deepspeech_binary_build
0
coqui_public_repos/inference-engine/third_party/kenlm
coqui_public_repos/inference-engine/third_party/kenlm/lm/value_build.cc
#include "lm/value_build.hh" #include "lm/model.hh" #include "lm/read_arpa.hh" namespace lm { namespace ngram { template <class Model> LowerRestBuild<Model>::LowerRestBuild(const Config &config, unsigned int order, const typename Model::Vocabulary &vocab) { UTIL_THROW_IF(config.rest_lower_files.size() != order - 1, ConfigException, "This model has order " << order << " so there should be " << (order - 1) << " lower-order models for rest cost purposes."); Config for_lower = config; for_lower.write_mmap = NULL; for_lower.rest_lower_files.clear(); // Unigram models aren't supported, so this is a custom loader. // TODO: optimize the unigram loading? { util::FilePiece uni(config.rest_lower_files[0].c_str()); std::vector<uint64_t> number; ReadARPACounts(uni, number); UTIL_THROW_IF(number.size() != 1, FormatLoadException, "Expected the unigram model to have order 1, not " << number.size()); ReadNGramHeader(uni, 1); unigrams_.resize(number[0]); unigrams_[0] = config.unknown_missing_logprob; PositiveProbWarn warn; for (uint64_t i = 0; i < number[0]; ++i) { WordIndex w; Prob entry; ReadNGram(uni, 1, vocab, &w, entry, warn); unigrams_[w] = entry.prob; } } try { for (unsigned int i = 2; i < order; ++i) { models_.push_back(new Model(config.rest_lower_files[i - 1].c_str(), for_lower)); UTIL_THROW_IF(models_.back()->Order() != i, FormatLoadException, "Lower order file " << config.rest_lower_files[i-1] << " should have order " << i); } } catch (...) { for (typename std::vector<const Model*>::const_iterator i = models_.begin(); i != models_.end(); ++i) { delete *i; } models_.clear(); throw; } // TODO: force/check same vocab. } template <class Model> LowerRestBuild<Model>::~LowerRestBuild() { for (typename std::vector<const Model*>::const_iterator i = models_.begin(); i != models_.end(); ++i) { delete *i; } } template class LowerRestBuild<ProbingModel>; } // namespace ngram } // namespace lm
0
coqui_public_repos/STT-models/estonian/itml
coqui_public_repos/STT-models/estonian/itml/v0.1.0/LICENSE
GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see <https://www.gnu.org/licenses/>.
0
coqui_public_repos/STT-models/dutch/acabunoc
coqui_public_repos/STT-models/dutch/acabunoc/v0.0.1/LICENSE
Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
0
coqui_public_repos
coqui_public_repos/TTS-papers/LICENSE
Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
0
coqui_public_repos/STT/native_client/kenlm
coqui_public_repos/STT/native_client/kenlm/lm/value_build.hh
#ifndef LM_VALUE_BUILD_H #define LM_VALUE_BUILD_H #include "weights.hh" #include "word_index.hh" #include "../util/bit_packing.hh" #include <vector> namespace lm { namespace ngram { struct Config; struct BackoffValue; struct RestValue; class NoRestBuild { public: typedef BackoffValue Value; NoRestBuild() {} void SetRest(const WordIndex *, unsigned int, const Prob &/*prob*/) const {} void SetRest(const WordIndex *, unsigned int, const ProbBackoff &) const {} template <class Second> bool MarkExtends(ProbBackoff &weights, const Second &) const { util::UnsetSign(weights.prob); return false; } // Probing doesn't need to go back to unigram. const static bool kMarkEvenLower = false; }; class MaxRestBuild { public: typedef RestValue Value; MaxRestBuild() {} void SetRest(const WordIndex *, unsigned int, const Prob &/*prob*/) const {} void SetRest(const WordIndex *, unsigned int, RestWeights &weights) const { weights.rest = weights.prob; util::SetSign(weights.rest); } bool MarkExtends(RestWeights &weights, const RestWeights &to) const { util::UnsetSign(weights.prob); if (weights.rest >= to.rest) return false; weights.rest = to.rest; return true; } bool MarkExtends(RestWeights &weights, const Prob &to) const { util::UnsetSign(weights.prob); if (weights.rest >= to.prob) return false; weights.rest = to.prob; return true; } // Probing does need to go back to unigram. const static bool kMarkEvenLower = true; }; template <class Model> class LowerRestBuild { public: typedef RestValue Value; LowerRestBuild(const Config &config, unsigned int order, const typename Model::Vocabulary &vocab); ~LowerRestBuild(); void SetRest(const WordIndex *, unsigned int, const Prob &/*prob*/) const {} void SetRest(const WordIndex *vocab_ids, unsigned int n, RestWeights &weights) const { typename Model::State ignored; if (n == 1) { weights.rest = unigrams_[*vocab_ids]; } else { weights.rest = models_[n-2]->FullScoreForgotState(vocab_ids + 1, vocab_ids + n, *vocab_ids, ignored).prob; } } template <class Second> bool MarkExtends(RestWeights &weights, const Second &) const { util::UnsetSign(weights.prob); return false; } const static bool kMarkEvenLower = false; std::vector<float> unigrams_; std::vector<const Model*> models_; }; } // namespace ngram } // namespace lm #endif // LM_VALUE_BUILD_H
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/mpdt/mpdtexpand.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Expands a (bounded-stack) MPDT as an FST. #include <cstring> #include <memory> #include <string> #include <vector> #include <fst/flags.h> #include <fst/log.h> #include <fst/extensions/mpdt/mpdtscript.h> #include <fst/extensions/mpdt/read_write_utils.h> #include <fst/util.h> DEFINE_string(mpdt_parentheses, "", "MPDT parenthesis label pairs with assignments"); DEFINE_bool(connect, true, "Trim output?"); DEFINE_bool(keep_parentheses, false, "Keep PDT parentheses in result?"); int main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::VectorFstClass; using fst::ReadLabelTriples; using fst::MPdtExpandOptions; string usage = "Expand a (bounded-stack) MPDT as an FST.\n\n Usage: "; usage += argv[0]; usage += " in.pdt [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && (strcmp(argv[1], "-") != 0)) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<FstClass> ifst(FstClass::Read(in_name)); if (!ifst) return 1; if (FLAGS_mpdt_parentheses.empty()) { LOG(ERROR) << argv[0] << ": No MPDT parenthesis label pairs provided"; return 1; } std::vector<s::LabelPair> parens; std::vector<int64> assignments; if (!ReadLabelTriples(FLAGS_mpdt_parentheses, &parens, &assignments, false)) return 1; VectorFstClass ofst(ifst->ArcType()); const MPdtExpandOptions opts(FLAGS_connect, FLAGS_keep_parentheses); s::MPdtExpand(*ifst, parens, assignments, &ofst, opts); ofst.Write(out_name); return 0; }
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions/mpdt/reverse.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Reverses an MPDT. #ifndef FST_EXTENSIONS_MPDT_REVERSE_H_ #define FST_EXTENSIONS_MPDT_REVERSE_H_ #include <limits> #include <vector> #include <fst/mutable-fst.h> #include <fst/relabel.h> #include <fst/reverse.h> namespace fst { // Reverses a multi-stack pushdown transducer (MPDT) encoded as an FST. template <class Arc, class RevArc> void Reverse( const Fst<Arc> &ifst, const std::vector<std::pair<typename Arc::Label, typename Arc::Label>> &parens, std::vector<typename Arc::Label> *assignments, MutableFst<RevArc> *ofst) { using Label = typename Arc::Label; // Reverses FST component. Reverse(ifst, ofst); // Exchanges open and close parenthesis pairs. std::vector<std::pair<Label, Label>> relabel_pairs; relabel_pairs.reserve(2 * parens.size()); for (const auto &pair : parens) { relabel_pairs.emplace_back(pair.first, pair.second); relabel_pairs.emplace_back(pair.second, pair.first); } Relabel(ofst, relabel_pairs, relabel_pairs); // Computes new bounds for the stack assignments. Label max_level = -1; Label min_level = std::numeric_limits<Label>::max(); for (const auto assignment : *assignments) { if (assignment < min_level) { min_level = assignment; } else if (assignment > max_level) { max_level = assignment; } } // Actually reverses stack assignments. for (auto &assignment : *assignments) { assignment = (max_level - assignment) + min_level; } } } // namespace fst #endif // FST_EXTENSIONS_MPDT_REVERSE_H_
0
coqui_public_repos/STT/native_client/kenlm/util
coqui_public_repos/STT/native_client/kenlm/util/double-conversion/strtod.cc
// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <climits> #include <cstdarg> #include "bignum.h" #include "cached-powers.h" #include "ieee.h" #include "strtod.h" namespace kenlm_double_conversion { #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) // 2^53 = 9007199254740992. // Any integer with at most 15 decimal digits will hence fit into a double // (which has a 53bit significand) without loss of precision. static const int kMaxExactDoubleIntegerDecimalDigits = 15; #endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) // 2^64 = 18446744073709551616 > 10^19 static const int kMaxUint64DecimalDigits = 19; // Max double: 1.7976931348623157 x 10^308 // Min non-zero double: 4.9406564584124654 x 10^-324 // Any x >= 10^309 is interpreted as +infinity. // Any x <= 10^-324 is interpreted as 0. // Note that 2.5e-324 (despite being smaller than the min double) will be read // as non-zero (equal to the min non-zero double). static const int kMaxDecimalPower = 309; static const int kMinDecimalPower = -324; // 2^64 = 18446744073709551616 static const uint64_t kMaxUint64 = DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF); #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) static const double exact_powers_of_ten[] = { 1.0, // 10^0 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, // 10^10 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 100000000000000000.0, 1000000000000000000.0, 10000000000000000000.0, 100000000000000000000.0, // 10^20 1000000000000000000000.0, // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22 10000000000000000000000.0 }; static const int kExactPowersOfTenSize = DOUBLE_CONVERSION_ARRAY_SIZE(exact_powers_of_ten); #endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) // Maximum number of significant digits in the decimal representation. // In fact the value is 772 (see conversions.cc), but to give us some margin // we round up to 780. static const int kMaxSignificantDecimalDigits = 780; static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) { for (int i = 0; i < buffer.length(); i++) { if (buffer[i] != '0') { return buffer.SubVector(i, buffer.length()); } } return Vector<const char>(buffer.start(), 0); } static void CutToMaxSignificantDigits(Vector<const char> buffer, int exponent, char* significant_buffer, int* significant_exponent) { for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) { significant_buffer[i] = buffer[i]; } // The input buffer has been trimmed. Therefore the last digit must be // different from '0'. DOUBLE_CONVERSION_ASSERT(buffer[buffer.length() - 1] != '0'); // Set the last digit to be non-zero. This is sufficient to guarantee // correct rounding. significant_buffer[kMaxSignificantDecimalDigits - 1] = '1'; *significant_exponent = exponent + (buffer.length() - kMaxSignificantDecimalDigits); } // Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits. // If possible the input-buffer is reused, but if the buffer needs to be // modified (due to cutting), then the input needs to be copied into the // buffer_copy_space. static void TrimAndCut(Vector<const char> buffer, int exponent, char* buffer_copy_space, int space_size, Vector<const char>* trimmed, int* updated_exponent) { Vector<const char> left_trimmed = TrimLeadingZeros(buffer); Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed); exponent += left_trimmed.length() - right_trimmed.length(); if (right_trimmed.length() > kMaxSignificantDecimalDigits) { (void) space_size; // Mark variable as used. DOUBLE_CONVERSION_ASSERT(space_size >= kMaxSignificantDecimalDigits); CutToMaxSignificantDigits(right_trimmed, exponent, buffer_copy_space, updated_exponent); *trimmed = Vector<const char>(buffer_copy_space, kMaxSignificantDecimalDigits); } else { *trimmed = right_trimmed; *updated_exponent = exponent; } } // Reads digits from the buffer and converts them to a uint64. // Reads in as many digits as fit into a uint64. // When the string starts with "1844674407370955161" no further digit is read. // Since 2^64 = 18446744073709551616 it would still be possible read another // digit if it was less or equal than 6, but this would complicate the code. static uint64_t ReadUint64(Vector<const char> buffer, int* number_of_read_digits) { uint64_t result = 0; int i = 0; while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) { int digit = buffer[i++] - '0'; DOUBLE_CONVERSION_ASSERT(0 <= digit && digit <= 9); result = 10 * result + digit; } *number_of_read_digits = i; return result; } // Reads a DiyFp from the buffer. // The returned DiyFp is not necessarily normalized. // If remaining_decimals is zero then the returned DiyFp is accurate. // Otherwise it has been rounded and has error of at most 1/2 ulp. static void ReadDiyFp(Vector<const char> buffer, DiyFp* result, int* remaining_decimals) { int read_digits; uint64_t significand = ReadUint64(buffer, &read_digits); if (buffer.length() == read_digits) { *result = DiyFp(significand, 0); *remaining_decimals = 0; } else { // Round the significand. if (buffer[read_digits] >= '5') { significand++; } // Compute the binary exponent. int exponent = 0; *result = DiyFp(significand, exponent); *remaining_decimals = buffer.length() - read_digits; } } static bool DoubleStrtod(Vector<const char> trimmed, int exponent, double* result) { #if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) // Avoid "unused parameter" warnings (void) trimmed; (void) exponent; (void) result; // On x86 the floating-point stack can be 64 or 80 bits wide. If it is // 80 bits wide (as is the case on Linux) then double-rounding occurs and the // result is not accurate. // We know that Windows32 uses 64 bits and is therefore accurate. return false; #else if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) { int read_digits; // The trimmed input fits into a double. // If the 10^exponent (resp. 10^-exponent) fits into a double too then we // can compute the result-double simply by multiplying (resp. dividing) the // two numbers. // This is possible because IEEE guarantees that floating-point operations // return the best possible approximation. if (exponent < 0 && -exponent < kExactPowersOfTenSize) { // 10^-exponent fits into a double. *result = static_cast<double>(ReadUint64(trimmed, &read_digits)); DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length()); *result /= exact_powers_of_ten[-exponent]; return true; } if (0 <= exponent && exponent < kExactPowersOfTenSize) { // 10^exponent fits into a double. *result = static_cast<double>(ReadUint64(trimmed, &read_digits)); DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length()); *result *= exact_powers_of_ten[exponent]; return true; } int remaining_digits = kMaxExactDoubleIntegerDecimalDigits - trimmed.length(); if ((0 <= exponent) && (exponent - remaining_digits < kExactPowersOfTenSize)) { // The trimmed string was short and we can multiply it with // 10^remaining_digits. As a result the remaining exponent now fits // into a double too. *result = static_cast<double>(ReadUint64(trimmed, &read_digits)); DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length()); *result *= exact_powers_of_ten[remaining_digits]; *result *= exact_powers_of_ten[exponent - remaining_digits]; return true; } } return false; #endif } // Returns 10^exponent as an exact DiyFp. // The given exponent must be in the range [1; kDecimalExponentDistance[. static DiyFp AdjustmentPowerOfTen(int exponent) { DOUBLE_CONVERSION_ASSERT(0 < exponent); DOUBLE_CONVERSION_ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance); // Simply hardcode the remaining powers for the given decimal exponent // distance. DOUBLE_CONVERSION_ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8); switch (exponent) { case 1: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xa0000000, 00000000), -60); case 2: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xc8000000, 00000000), -57); case 3: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xfa000000, 00000000), -54); case 4: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0x9c400000, 00000000), -50); case 5: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xc3500000, 00000000), -47); case 6: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xf4240000, 00000000), -44); case 7: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0x98968000, 00000000), -40); default: DOUBLE_CONVERSION_UNREACHABLE(); } } // If the function returns true then the result is the correct double. // Otherwise it is either the correct double or the double that is just below // the correct double. static bool DiyFpStrtod(Vector<const char> buffer, int exponent, double* result) { DiyFp input; int remaining_decimals; ReadDiyFp(buffer, &input, &remaining_decimals); // Since we may have dropped some digits the input is not accurate. // If remaining_decimals is different than 0 than the error is at most // .5 ulp (unit in the last place). // We don't want to deal with fractions and therefore keep a common // denominator. const int kDenominatorLog = 3; const int kDenominator = 1 << kDenominatorLog; // Move the remaining decimals into the exponent. exponent += remaining_decimals; uint64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2); int old_e = input.e(); input.Normalize(); error <<= old_e - input.e(); DOUBLE_CONVERSION_ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent); if (exponent < PowersOfTenCache::kMinDecimalExponent) { *result = 0.0; return true; } DiyFp cached_power; int cached_decimal_exponent; PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent, &cached_power, &cached_decimal_exponent); if (cached_decimal_exponent != exponent) { int adjustment_exponent = exponent - cached_decimal_exponent; DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent); input.Multiply(adjustment_power); if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) { // The product of input with the adjustment power fits into a 64 bit // integer. DOUBLE_CONVERSION_ASSERT(DiyFp::kSignificandSize == 64); } else { // The adjustment power is exact. There is hence only an error of 0.5. error += kDenominator / 2; } } input.Multiply(cached_power); // The error introduced by a multiplication of a*b equals // error_a + error_b + error_a*error_b/2^64 + 0.5 // Substituting a with 'input' and b with 'cached_power' we have // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp), // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64 int error_b = kDenominator / 2; int error_ab = (error == 0 ? 0 : 1); // We round up to 1. int fixed_error = kDenominator / 2; error += error_b + error_ab + fixed_error; old_e = input.e(); input.Normalize(); error <<= old_e - input.e(); // See if the double's significand changes if we add/subtract the error. int order_of_magnitude = DiyFp::kSignificandSize + input.e(); int effective_significand_size = Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude); int precision_digits_count = DiyFp::kSignificandSize - effective_significand_size; if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) { // This can only happen for very small denormals. In this case the // half-way multiplied by the denominator exceeds the range of an uint64. // Simply shift everything to the right. int shift_amount = (precision_digits_count + kDenominatorLog) - DiyFp::kSignificandSize + 1; input.set_f(input.f() >> shift_amount); input.set_e(input.e() + shift_amount); // We add 1 for the lost precision of error, and kDenominator for // the lost precision of input.f(). error = (error >> shift_amount) + 1 + kDenominator; precision_digits_count -= shift_amount; } // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too. DOUBLE_CONVERSION_ASSERT(DiyFp::kSignificandSize == 64); DOUBLE_CONVERSION_ASSERT(precision_digits_count < 64); uint64_t one64 = 1; uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1; uint64_t precision_bits = input.f() & precision_bits_mask; uint64_t half_way = one64 << (precision_digits_count - 1); precision_bits *= kDenominator; half_way *= kDenominator; DiyFp rounded_input(input.f() >> precision_digits_count, input.e() + precision_digits_count); if (precision_bits >= half_way + error) { rounded_input.set_f(rounded_input.f() + 1); } // If the last_bits are too close to the half-way case than we are too // inaccurate and round down. In this case we return false so that we can // fall back to a more precise algorithm. *result = Double(rounded_input).value(); if (half_way - error < precision_bits && precision_bits < half_way + error) { // Too imprecise. The caller will have to fall back to a slower version. // However the returned number is guaranteed to be either the correct // double, or the next-lower double. return false; } else { return true; } } // Returns // - -1 if buffer*10^exponent < diy_fp. // - 0 if buffer*10^exponent == diy_fp. // - +1 if buffer*10^exponent > diy_fp. // Preconditions: // buffer.length() + exponent <= kMaxDecimalPower + 1 // buffer.length() + exponent > kMinDecimalPower // buffer.length() <= kMaxDecimalSignificantDigits static int CompareBufferWithDiyFp(Vector<const char> buffer, int exponent, DiyFp diy_fp) { DOUBLE_CONVERSION_ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1); DOUBLE_CONVERSION_ASSERT(buffer.length() + exponent > kMinDecimalPower); DOUBLE_CONVERSION_ASSERT(buffer.length() <= kMaxSignificantDecimalDigits); // Make sure that the Bignum will be able to hold all our numbers. // Our Bignum implementation has a separate field for exponents. Shifts will // consume at most one bigit (< 64 bits). // ln(10) == 3.3219... DOUBLE_CONVERSION_ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits); Bignum buffer_bignum; Bignum diy_fp_bignum; buffer_bignum.AssignDecimalString(buffer); diy_fp_bignum.AssignUInt64(diy_fp.f()); if (exponent >= 0) { buffer_bignum.MultiplyByPowerOfTen(exponent); } else { diy_fp_bignum.MultiplyByPowerOfTen(-exponent); } if (diy_fp.e() > 0) { diy_fp_bignum.ShiftLeft(diy_fp.e()); } else { buffer_bignum.ShiftLeft(-diy_fp.e()); } return Bignum::Compare(buffer_bignum, diy_fp_bignum); } // Returns true if the guess is the correct double. // Returns false, when guess is either correct or the next-lower double. static bool ComputeGuess(Vector<const char> trimmed, int exponent, double* guess) { if (trimmed.length() == 0) { *guess = 0.0; return true; } if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) { *guess = Double::Infinity(); return true; } if (exponent + trimmed.length() <= kMinDecimalPower) { *guess = 0.0; return true; } if (DoubleStrtod(trimmed, exponent, guess) || DiyFpStrtod(trimmed, exponent, guess)) { return true; } if (*guess == Double::Infinity()) { return true; } return false; } static bool IsDigit(const char d) { return ('0' <= d) && (d <= '9'); } static bool IsNonZeroDigit(const char d) { return ('1' <= d) && (d <= '9'); } #ifdef __has_cpp_attribute #if __has_cpp_attribute(maybe_unused) [[maybe_unused]] #endif #endif static bool AssertTrimmedDigits(const Vector<const char>& buffer) { for(int i = 0; i < buffer.length(); ++i) { if(!IsDigit(buffer[i])) { return false; } } return (buffer.length() == 0) || (IsNonZeroDigit(buffer[0]) && IsNonZeroDigit(buffer[buffer.length()-1])); } double StrtodTrimmed(Vector<const char> trimmed, int exponent) { DOUBLE_CONVERSION_ASSERT(trimmed.length() <= kMaxSignificantDecimalDigits); DOUBLE_CONVERSION_ASSERT(AssertTrimmedDigits(trimmed)); double guess; const bool is_correct = ComputeGuess(trimmed, exponent, &guess); if (is_correct) { return guess; } DiyFp upper_boundary = Double(guess).UpperBoundary(); int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary); if (comparison < 0) { return guess; } else if (comparison > 0) { return Double(guess).NextDouble(); } else if ((Double(guess).Significand() & 1) == 0) { // Round towards even. return guess; } else { return Double(guess).NextDouble(); } } double Strtod(Vector<const char> buffer, int exponent) { char copy_buffer[kMaxSignificantDecimalDigits]; Vector<const char> trimmed; int updated_exponent; TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits, &trimmed, &updated_exponent); return StrtodTrimmed(trimmed, updated_exponent); } static float SanitizedDoubletof(double d) { DOUBLE_CONVERSION_ASSERT(d >= 0.0); // ASAN has a sanitize check that disallows casting doubles to floats if // they are too big. // https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks // The behavior should be covered by IEEE 754, but some projects use this // flag, so work around it. float max_finite = 3.4028234663852885981170418348451692544e+38; // The half-way point between the max-finite and infinity value. // Since infinity has an even significand everything equal or greater than // this value should become infinity. double half_max_finite_infinity = 3.40282356779733661637539395458142568448e+38; if (d >= max_finite) { if (d >= half_max_finite_infinity) { return Single::Infinity(); } else { return max_finite; } } else { return static_cast<float>(d); } } float Strtof(Vector<const char> buffer, int exponent) { char copy_buffer[kMaxSignificantDecimalDigits]; Vector<const char> trimmed; int updated_exponent; TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits, &trimmed, &updated_exponent); exponent = updated_exponent; return StrtofTrimmed(trimmed, exponent); } float StrtofTrimmed(Vector<const char> trimmed, int exponent) { DOUBLE_CONVERSION_ASSERT(trimmed.length() <= kMaxSignificantDecimalDigits); DOUBLE_CONVERSION_ASSERT(AssertTrimmedDigits(trimmed)); double double_guess; bool is_correct = ComputeGuess(trimmed, exponent, &double_guess); float float_guess = SanitizedDoubletof(double_guess); if (float_guess == double_guess) { // This shortcut triggers for integer values. return float_guess; } // We must catch double-rounding. Say the double has been rounded up, and is // now a boundary of a float, and rounds up again. This is why we have to // look at previous too. // Example (in decimal numbers): // input: 12349 // high-precision (4 digits): 1235 // low-precision (3 digits): // when read from input: 123 // when rounded from high precision: 124. // To do this we simply look at the neighbors of the correct result and see // if they would round to the same float. If the guess is not correct we have // to look at four values (since two different doubles could be the correct // double). double double_next = Double(double_guess).NextDouble(); double double_previous = Double(double_guess).PreviousDouble(); float f1 = SanitizedDoubletof(double_previous); float f2 = float_guess; float f3 = SanitizedDoubletof(double_next); float f4; if (is_correct) { f4 = f3; } else { double double_next2 = Double(double_next).NextDouble(); f4 = SanitizedDoubletof(double_next2); } (void) f2; // Mark variable as used. DOUBLE_CONVERSION_ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4); // If the guess doesn't lie near a single-precision boundary we can simply // return its float-value. if (f1 == f4) { return float_guess; } DOUBLE_CONVERSION_ASSERT((f1 != f2 && f2 == f3 && f3 == f4) || (f1 == f2 && f2 != f3 && f3 == f4) || (f1 == f2 && f2 == f3 && f3 != f4)); // guess and next are the two possible candidates (in the same way that // double_guess was the lower candidate for a double-precision guess). float guess = f1; float next = f4; DiyFp upper_boundary; if (guess == 0.0f) { float min_float = 1e-45f; upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp(); } else { upper_boundary = Single(guess).UpperBoundary(); } int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary); if (comparison < 0) { return guess; } else if (comparison > 0) { return next; } else if ((Single(guess).Significand() & 1) == 0) { // Round towards even. return guess; } else { return next; } } } // namespace kenlm_double_conversion
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstmap-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Applies an operation to each arc of an FST. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/log.h> #include <fst/script/getters.h> #include <fst/script/map.h> DECLARE_double(delta); DECLARE_string(map_type); DECLARE_double(power); DECLARE_string(weight); int fstmap_main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::WeightClass; string usage = "Applies an operation to each arc of an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<FstClass> ifst(FstClass::Read(in_name)); if (!ifst) return 1; s::MapType map_type; if (!s::GetMapType(FLAGS_map_type, &map_type)) { LOG(ERROR) << argv[0] << ": Unknown or unsupported map type " << FLAGS_map_type; return 1; } const auto weight_param = !FLAGS_weight.empty() ? WeightClass(ifst->WeightType(), FLAGS_weight) : (FLAGS_map_type == "times" ? WeightClass::One(ifst->WeightType()) : WeightClass::Zero(ifst->WeightType())); std::unique_ptr<FstClass> ofst( s::Map(*ifst, map_type, FLAGS_delta, FLAGS_power, weight_param)); return !ofst->Write(out_name); }
0
coqui_public_repos/TTS/tests
coqui_public_repos/TTS/tests/text_tests/test_belarusian_phonemizer.py
import os import unittest import warnings from TTS.tts.utils.text.belarusian.phonemizer import belarusian_text_to_phonemes _TEST_CASES = """ Фанетычны канвертар/fanʲɛˈtɨt͡ʂnɨ kanˈvʲɛrtar Гэтак мы працавалі/ˈɣɛtak ˈmɨ prat͡saˈvalʲi """ class TestText(unittest.TestCase): def test_belarusian_text_to_phonemes(self): try: os.environ["BEL_FANETYKA_JAR"] except KeyError: warnings.warn( "You need to define 'BEL_FANETYKA_JAR' environment variable as path to the fanetyka.jar file to test Belarusian phonemizer", Warning, ) return for line in _TEST_CASES.strip().split("\n"): text, phonemes = line.split("/") self.assertEqual(belarusian_text_to_phonemes(text), phonemes) if __name__ == "__main__": unittest.main()
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-nodejs_14x_16k_multiarchpkg-linux-amd64-opt.yml
build: template_file: test-linux-opt-base.tyml docker_image: "ubuntu:16.04" dependencies: - "node-package-cpu" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${nodejs.packages_xenial.prep_14} && ${nodejs.packages_xenial.apt_pinning} && apt-get -qq update && apt-get -qq -y install ${nodejs.packages_xenial.apt} args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-node-tests.sh 14.x 16k" workerType: "${docker.dsTests}" metadata: name: "DeepSpeech Linux AMD64 CPU NodeJS MultiArch Package 14.x tests (16kHz)" description: "Testing DeepSpeech for Linux/AMD64 on NodeJS MultiArch Package v14.x, CPU only, optimized version (16kHz)"
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/extensions/far/sttable.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // A generic string-to-type table file format. // // This is not meant as a generalization of SSTable. This is more of a simple // replacement for SSTable in order to provide an open-source implementation // of the FAR format for the external version of the FST library. #ifndef FST_EXTENSIONS_FAR_STTABLE_H_ #define FST_EXTENSIONS_FAR_STTABLE_H_ #include <algorithm> #include <istream> #include <memory> #include <fstream> #include <fst/util.h> namespace fst { static constexpr int32 kSTTableMagicNumber = 2125656924; static constexpr int32 kSTTableFileVersion = 1; // String-type table writing class for an object of type T using a functor // Writer. The Writer functor must provide at least the following interface: // // struct Writer { // void operator()(std::ostream &, const T &) const; // }; template <class T, class Writer> class STTableWriter { public: explicit STTableWriter(const string &filename) : stream_(filename, std::ios_base::out | std::ios_base::binary), error_(false) { WriteType(stream_, kSTTableMagicNumber); WriteType(stream_, kSTTableFileVersion); if (stream_.fail()) { FSTERROR() << "STTableWriter::STTableWriter: Error writing to file: " << filename; error_ = true; } } static STTableWriter<T, Writer> *Create(const string &filename) { if (filename.empty()) { LOG(ERROR) << "STTableWriter: Writing to standard out unsupported."; return nullptr; } return new STTableWriter<T, Writer>(filename); } void Add(const string &key, const T &t) { if (key == "") { FSTERROR() << "STTableWriter::Add: Key empty: " << key; error_ = true; } else if (key < last_key_) { FSTERROR() << "STTableWriter::Add: Key out of order: " << key; error_ = true; } if (error_) return; last_key_ = key; positions_.push_back(stream_.tellp()); WriteType(stream_, key); entry_writer_(stream_, t); } bool Error() const { return error_; } ~STTableWriter() { WriteType(stream_, positions_); WriteType(stream_, static_cast<int64>(positions_.size())); } private: Writer entry_writer_; std::ofstream stream_; std::vector<int64> positions_; // Position in file of each key-entry pair. string last_key_; // Last key. bool error_; STTableWriter(const STTableWriter &) = delete; STTableWriter &operator=(const STTableWriter &) = delete; }; // String-type table reading class for object of type T using a functor Reader. // Reader must provide at least the following interface: // // struct Reader { // T *operator()(std::istream &) const; // }; // template <class T, class Reader> class STTableReader { public: explicit STTableReader(const std::vector<string> &filenames) : sources_(filenames), error_(false) { compare_.reset(new Compare(&keys_)); keys_.resize(filenames.size()); streams_.resize(filenames.size(), 0); positions_.resize(filenames.size()); for (size_t i = 0; i < filenames.size(); ++i) { streams_[i] = new std::ifstream( filenames[i], std::ios_base::in | std::ios_base::binary); int32 magic_number = 0; ReadType(*streams_[i], &magic_number); int32 file_version = 0; ReadType(*streams_[i], &file_version); if (magic_number != kSTTableMagicNumber) { FSTERROR() << "STTableReader::STTableReader: Wrong file type: " << filenames[i]; error_ = true; return; } if (file_version != kSTTableFileVersion) { FSTERROR() << "STTableReader::STTableReader: Wrong file version: " << filenames[i]; error_ = true; return; } int64 num_entries; streams_[i]->seekg(-static_cast<int>(sizeof(int64)), std::ios_base::end); ReadType(*streams_[i], &num_entries); if (num_entries > 0) { streams_[i]->seekg(-static_cast<int>(sizeof(int64)) * (num_entries + 1), std::ios_base::end); positions_[i].resize(num_entries); for (size_t j = 0; (j < num_entries) && (!streams_[i]->fail()); ++j) { ReadType(*streams_[i], &(positions_[i][j])); } streams_[i]->seekg(positions_[i][0]); if (streams_[i]->fail()) { FSTERROR() << "STTableReader::STTableReader: Error reading file: " << filenames[i]; error_ = true; return; } } } MakeHeap(); } ~STTableReader() { for (auto &stream : streams_) delete stream; } static STTableReader<T, Reader> *Open(const string &filename) { if (filename.empty()) { LOG(ERROR) << "STTableReader: Operation not supported on standard input"; return nullptr; } std::vector<string> filenames; filenames.push_back(filename); return new STTableReader<T, Reader>(filenames); } static STTableReader<T, Reader> *Open(const std::vector<string> &filenames) { return new STTableReader<T, Reader>(filenames); } void Reset() { if (error_) return; for (size_t i = 0; i < streams_.size(); ++i) streams_[i]->seekg(positions_[i].front()); MakeHeap(); } bool Find(const string &key) { if (error_) return false; for (size_t i = 0; i < streams_.size(); ++i) LowerBound(i, key); MakeHeap(); if (heap_.empty()) return false; return keys_[current_] == key; } bool Done() const { return error_ || heap_.empty(); } void Next() { if (error_) return; if (streams_[current_]->tellg() <= positions_[current_].back()) { ReadType(*(streams_[current_]), &(keys_[current_])); if (streams_[current_]->fail()) { FSTERROR() << "STTableReader: Error reading file: " << sources_[current_]; error_ = true; return; } std::push_heap(heap_.begin(), heap_.end(), *compare_); } else { heap_.pop_back(); } if (!heap_.empty()) PopHeap(); } const string &GetKey() const { return keys_[current_]; } const T *GetEntry() const { return entry_.get(); } bool Error() const { return error_; } private: // Comparison functor used to compare stream IDs in the heap. struct Compare { explicit Compare(const std::vector<string> *keys) : keys(keys) {} bool operator()(size_t i, size_t j) const { return (*keys)[i] > (*keys)[j]; }; private: const std::vector<string> *keys; }; // Positions the stream at the position corresponding to the lower bound for // the specified key. void LowerBound(size_t id, const string &find_key) { auto *strm = streams_[id]; const auto &positions = positions_[id]; if (positions.empty()) return; size_t low = 0; size_t high = positions.size() - 1; while (low < high) { size_t mid = (low + high) / 2; strm->seekg(positions[mid]); string key; ReadType(*strm, &key); if (key > find_key) { high = mid; } else if (key < find_key) { low = mid + 1; } else { for (size_t i = mid; i > low; --i) { strm->seekg(positions[i - 1]); ReadType(*strm, &key); if (key != find_key) { strm->seekg(positions[i]); return; } } strm->seekg(positions[low]); return; } } strm->seekg(positions[low]); } // Adds all streams to the heap. void MakeHeap() { heap_.clear(); for (size_t i = 0; i < streams_.size(); ++i) { if (positions_[i].empty()) continue; ReadType(*streams_[i], &(keys_[i])); if (streams_[i]->fail()) { FSTERROR() << "STTableReader: Error reading file: " << sources_[i]; error_ = true; return; } heap_.push_back(i); } if (heap_.empty()) return; std::make_heap(heap_.begin(), heap_.end(), *compare_); PopHeap(); } // Positions the stream with the lowest key at the top of the heap, sets // current_ to the ID of that stream, and reads the current entry from that // stream. void PopHeap() { std::pop_heap(heap_.begin(), heap_.end(), *compare_); current_ = heap_.back(); entry_.reset(entry_reader_(*streams_[current_])); if (!entry_) error_ = true; if (streams_[current_]->fail()) { FSTERROR() << "STTableReader: Error reading entry for key: " << keys_[current_] << ", file: " << sources_[current_]; error_ = true; } } Reader entry_reader_; std::vector<std::istream *> streams_; // Input streams. std::vector<string> sources_; // Corresponding file names. std::vector<std::vector<int64>> positions_; // Index of positions. std::vector<string> keys_; // Lowest unread key for each stream. std::vector<int64> heap_; // Heap containing ID of streams with unread keys. int64 current_; // ID of current stream to be read. std::unique_ptr<Compare> compare_; // Functor comparing stream IDs. mutable std::unique_ptr<T> entry_; // The currently read entry. bool error_; }; // String-type table header reading function template on the entry header type. // The Header type must provide at least the following interface: // // struct Header { // void Read(std::istream &istrm, const string &filename); // }; template <class Header> bool ReadSTTableHeader(const string &filename, Header *header) { if (filename.empty()) { LOG(ERROR) << "ReadSTTable: Can't read header from standard input"; return false; } std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary); if (!strm) { LOG(ERROR) << "ReadSTTableHeader: Could not open file: " << filename; return false; } int32 magic_number = 0; ReadType(strm, &magic_number); int32 file_version = 0; ReadType(strm, &file_version); if (magic_number != kSTTableMagicNumber) { LOG(ERROR) << "ReadSTTableHeader: Wrong file type: " << filename; return false; } if (file_version != kSTTableFileVersion) { LOG(ERROR) << "ReadSTTableHeader: Wrong file version: " << filename; return false; } int64 i = -1; strm.seekg(-static_cast<int>(sizeof(int64)), std::ios_base::end); ReadType(strm, &i); // Reads number of entries if (strm.fail()) { LOG(ERROR) << "ReadSTTableHeader: Error reading file: " << filename; return false; } if (i == 0) return true; // No entry header to read. strm.seekg(-2 * static_cast<int>(sizeof(int64)), std::ios_base::end); ReadType(strm, &i); // Reads position for last entry in file. strm.seekg(i); string key; ReadType(strm, &key); header->Read(strm, filename + ":" + key); if (strm.fail()) { LOG(ERROR) << "ReadSTTableHeader: Error reading file: " << filename; return false; } return true; } bool IsSTTable(const string &filename); } // namespace fst #endif // FST_EXTENSIONS_FAR_STTABLE_H_
0
coqui_public_repos/inference-engine/third_party
coqui_public_repos/inference-engine/third_party/kenlm/setup.py
from setuptools import setup, Extension import glob import platform import os import sys import re #Does gcc compile with this header and library? def compile_test(header, library): dummy_path = os.path.join(os.path.dirname(__file__), "dummy") command = "bash -c \"g++ -include " + header + " -l" + library + " -x c++ - <<<'int main() {}' -o " + dummy_path + " >/dev/null 2>/dev/null && rm " + dummy_path + " 2>/dev/null\"" return os.system(command) == 0 max_order = "6" is_max_order = [s for s in sys.argv if "--max_order" in s] for element in is_max_order: max_order = re.split('[= ]',element)[1] sys.argv.remove(element) FILES = glob.glob('util/*.cc') + glob.glob('lm/*.cc') + glob.glob('util/double-conversion/*.cc') + glob.glob('python/*.cc') FILES = [fn for fn in FILES if not (fn.endswith('main.cc') or fn.endswith('test.cc'))] if platform.system() == 'Linux': LIBS = ['stdc++', 'rt'] elif platform.system() == 'Darwin': LIBS = ['c++'] else: LIBS = [] #We don't need -std=c++11 but python seems to be compiled with it now. https://github.com/kpu/kenlm/issues/86 ARGS = ['-O3', '-DNDEBUG', '-DKENLM_MAX_ORDER='+max_order, '-std=c++11'] #Attempted fix to https://github.com/kpu/kenlm/issues/186 and https://github.com/kpu/kenlm/issues/197 if platform.system() == 'Darwin': ARGS += ["-stdlib=libc++", "-mmacosx-version-min=10.7"] if compile_test('zlib.h', 'z'): ARGS.append('-DHAVE_ZLIB') LIBS.append('z') if compile_test('bzlib.h', 'bz2'): ARGS.append('-DHAVE_BZLIB') LIBS.append('bz2') if compile_test('lzma.h', 'lzma'): ARGS.append('-DHAVE_XZLIB') LIBS.append('lzma') ext_modules = [ Extension(name='kenlm', sources=FILES + ['python/kenlm.cpp'], language='C++', include_dirs=['.'], libraries=LIBS, extra_compile_args=ARGS) ] setup( name='kenlm', ext_modules=ext_modules, include_package_data=True, )
0
coqui_public_repos/STT-models/dhivehi/itml
coqui_public_repos/STT-models/dhivehi/itml/v0.1.0/alphabet.txt
ހ ށ ނ ރ ބ ޅ ކ އ ވ މ ފ ދ ތ ލ ގ ޏ ސ ޑ ޒ ޓ ޔ ޕ ޖ ޗ ޘ ޙ ޚ ޛ ޜ ޝ ޞ ޟ ޠ ޡ ޢ ޣ ޤ ޥ ަ ާ ި ީ ު ޫ ެ ޭ ޮ ޯ ް
0
coqui_public_repos/TTS/TTS/tts/utils/text
coqui_public_repos/TTS/TTS/tts/utils/text/phonemizers/multi_phonemizer.py
from typing import Dict, List from TTS.tts.utils.text.phonemizers import DEF_LANG_TO_PHONEMIZER, get_phonemizer_by_name class MultiPhonemizer: """🐸TTS multi-phonemizer that operates phonemizers for multiple langugages Args: custom_lang_to_phonemizer (Dict): Custom phonemizer mapping if you want to change the defaults. In the format of `{"lang_code", "phonemizer_name"}`. When it is None, `DEF_LANG_TO_PHONEMIZER` is used. Defaults to `{}`. TODO: find a way to pass custom kwargs to the phonemizers """ lang_to_phonemizer = {} def __init__(self, lang_to_phonemizer_name: Dict = {}) -> None: # pylint: disable=dangerous-default-value for k, v in lang_to_phonemizer_name.items(): if v == "" and k in DEF_LANG_TO_PHONEMIZER.keys(): lang_to_phonemizer_name[k] = DEF_LANG_TO_PHONEMIZER[k] elif v == "": raise ValueError(f"Phonemizer wasn't set for language {k} and doesn't have a default.") self.lang_to_phonemizer_name = lang_to_phonemizer_name self.lang_to_phonemizer = self.init_phonemizers(self.lang_to_phonemizer_name) @staticmethod def init_phonemizers(lang_to_phonemizer_name: Dict) -> Dict: lang_to_phonemizer = {} for k, v in lang_to_phonemizer_name.items(): lang_to_phonemizer[k] = get_phonemizer_by_name(v, language=k) return lang_to_phonemizer @staticmethod def name(): return "multi-phonemizer" def phonemize(self, text, separator="|", language=""): if language == "": raise ValueError("Language must be set for multi-phonemizer to phonemize.") return self.lang_to_phonemizer[language].phonemize(text, separator) def supported_languages(self) -> List: return list(self.lang_to_phonemizer.keys()) def print_logs(self, level: int = 0): indent = "\t" * level print(f"{indent}| > phoneme language: {self.supported_languages()}") print(f"{indent}| > phoneme backend: {self.name()}") # if __name__ == "__main__": # texts = { # "tr": "Merhaba, bu Türkçe bit örnek!", # "en-us": "Hello, this is English example!", # "de": "Hallo, das ist ein Deutches Beipiel!", # "zh-cn": "这是中国的例子", # } # phonemes = {} # ph = MultiPhonemizer({"tr": "espeak", "en-us": "", "de": "gruut", "zh-cn": ""}) # for lang, text in texts.items(): # phoneme = ph.phonemize(text, lang) # phonemes[lang] = phoneme # print(phonemes)
0
coqui_public_repos/TTS/TTS/vocoder
coqui_public_repos/TTS/TTS/vocoder/configs/multiband_melgan_config.py
from dataclasses import dataclass, field from TTS.vocoder.configs.shared_configs import BaseGANVocoderConfig @dataclass class MultibandMelganConfig(BaseGANVocoderConfig): """Defines parameters for MultiBandMelGAN vocoder. Example: >>> from TTS.vocoder.configs import MultibandMelganConfig >>> config = MultibandMelganConfig() Args: model (str): Model name used for selecting the right model at initialization. Defaults to `multiband_melgan`. discriminator_model (str): One of the discriminators from `TTS.vocoder.models.*_discriminator`. Defaults to 'melgan_multiscale_discriminator`. discriminator_model_params (dict): The discriminator model parameters. Defaults to '{ "base_channels": 16, "max_channels": 512, "downsample_factors": [4, 4, 4] }` generator_model (str): One of the generators from TTS.vocoder.models.*`. Every other non-GAN vocoder model is considered as a generator too. Defaults to `melgan_generator`. generator_model_param (dict): The generator model parameters. Defaults to `{"upsample_factors": [8, 4, 2], "num_res_blocks": 4}`. use_pqmf (bool): enable / disable PQMF modulation for multi-band training. Defaults to True. lr_gen (float): Initial learning rate for the generator model. Defaults to 0.0001. lr_disc (float): Initial learning rate for the discriminator model. Defaults to 0.0001. optimizer (torch.optim.Optimizer): Optimizer used for the training. Defaults to `AdamW`. optimizer_params (dict): Optimizer kwargs. Defaults to `{"betas": [0.8, 0.99], "weight_decay": 0.0}` lr_scheduler_gen (torch.optim.Scheduler): Learning rate scheduler for the generator. Defaults to `MultiStepLR`. lr_scheduler_gen_params (dict): Parameters for the generator learning rate scheduler. Defaults to `{"gamma": 0.5, "milestones": [100000, 200000, 300000, 400000, 500000, 600000]}`. lr_scheduler_disc (torch.optim.Scheduler): Learning rate scheduler for the discriminator. Defaults to `MultiStepLR`. lr_scheduler_dict_params (dict): Parameters for the discriminator learning rate scheduler. Defaults to `{"gamma": 0.5, "milestones": [100000, 200000, 300000, 400000, 500000, 600000]}`. batch_size (int): Batch size used at training. Larger values use more memory. Defaults to 16. seq_len (int): Audio segment length used at training. Larger values use more memory. Defaults to 8192. pad_short (int): Additional padding applied to the audio samples shorter than `seq_len`. Defaults to 0. use_noise_augment (bool): enable / disable random noise added to the input waveform. The noise is added after computing the features. Defaults to True. use_cache (bool): enable / disable in memory caching of the computed features. It can cause OOM error if the system RAM is not large enough. Defaults to True. steps_to_start_discriminator (int): Number of steps required to start training the discriminator. Defaults to 0. use_stft_loss (bool):` enable / disable use of STFT loss originally used by ParallelWaveGAN model. Defaults to True. use_subband_stft (bool): enable / disable use of subband loss computation originally used by MultiBandMelgan model. Defaults to True. use_mse_gan_loss (bool): enable / disable using Mean Squeare Error GAN loss. Defaults to True. use_hinge_gan_loss (bool): enable / disable using Hinge GAN loss. You should choose either Hinge or MSE loss for training GAN models. Defaults to False. use_feat_match_loss (bool): enable / disable using Feature Matching loss originally used by MelGAN model. Defaults to True. use_l1_spec_loss (bool): enable / disable using L1 spectrogram loss originally used by HifiGAN model. Defaults to False. stft_loss_params (dict): STFT loss parameters. Default to `{"n_ffts": [1024, 2048, 512], "hop_lengths": [120, 240, 50], "win_lengths": [600, 1200, 240]}` stft_loss_weight (float): STFT loss weight that multiplies the computed loss before summing up the total model loss. Defaults to 0.5. subband_stft_loss_weight (float): Subband STFT loss weight that multiplies the computed loss before summing up the total loss. Defaults to 0. mse_G_loss_weight (float): MSE generator loss weight that multiplies the computed loss before summing up the total loss. faults to 2.5. hinge_G_loss_weight (float): Hinge generator loss weight that multiplies the computed loss before summing up the total loss. Defaults to 0. feat_match_loss_weight (float): Feature matching loss weight that multiplies the computed loss before summing up the total loss. faults to 108. l1_spec_loss_weight (float): L1 spectrogram loss weight that multiplies the computed loss before summing up the total loss. Defaults to 0. """ model: str = "multiband_melgan" # Model specific params discriminator_model: str = "melgan_multiscale_discriminator" discriminator_model_params: dict = field( default_factory=lambda: {"base_channels": 16, "max_channels": 512, "downsample_factors": [4, 4, 4]} ) generator_model: str = "multiband_melgan_generator" generator_model_params: dict = field(default_factory=lambda: {"upsample_factors": [8, 4, 2], "num_res_blocks": 4}) use_pqmf: bool = True # optimizer - overrides lr_gen: float = 0.0001 # Initial learning rate. lr_disc: float = 0.0001 # Initial learning rate. optimizer: str = "AdamW" optimizer_params: dict = field(default_factory=lambda: {"betas": [0.8, 0.99], "weight_decay": 0.0}) lr_scheduler_gen: str = "MultiStepLR" # one of the schedulers from https:#pytorch.org/docs/stable/optim.html lr_scheduler_gen_params: dict = field( default_factory=lambda: {"gamma": 0.5, "milestones": [100000, 200000, 300000, 400000, 500000, 600000]} ) lr_scheduler_disc: str = "MultiStepLR" # one of the schedulers from https:#pytorch.org/docs/stable/optim.html lr_scheduler_disc_params: dict = field( default_factory=lambda: {"gamma": 0.5, "milestones": [100000, 200000, 300000, 400000, 500000, 600000]} ) # Training - overrides batch_size: int = 64 seq_len: int = 16384 pad_short: int = 2000 use_noise_augment: bool = False use_cache: bool = True steps_to_start_discriminator: bool = 200000 # LOSS PARAMETERS - overrides use_stft_loss: bool = True use_subband_stft_loss: bool = True use_mse_gan_loss: bool = True use_hinge_gan_loss: bool = False use_feat_match_loss: bool = False # requires MelGAN Discriminators (MelGAN and HifiGAN) use_l1_spec_loss: bool = False subband_stft_loss_params: dict = field( default_factory=lambda: {"n_ffts": [384, 683, 171], "hop_lengths": [30, 60, 10], "win_lengths": [150, 300, 60]} ) # loss weights - overrides stft_loss_weight: float = 0.5 subband_stft_loss_weight: float = 0 mse_G_loss_weight: float = 2.5 hinge_G_loss_weight: float = 0 feat_match_loss_weight: float = 108 l1_spec_loss_weight: float = 0
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/script/fst-class.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // These classes are only recommended for use in high-level scripting // applications. Most users should use the lower-level templated versions // corresponding to these classes. #include <istream> #include <fst/log.h> #include <fst/equal.h> #include <fst/fst-decl.h> #include <fst/reverse.h> #include <fst/union.h> #include <fst/script/fst-class.h> #include <fst/script/register.h> namespace fst { namespace script { // Registration. REGISTER_FST_CLASSES(StdArc); REGISTER_FST_CLASSES(LogArc); REGISTER_FST_CLASSES(Log64Arc); // Helper functions. namespace { template <class F> F *ReadFstClass(std::istream &istrm, const string &fname) { if (!istrm) { LOG(ERROR) << "ReadFstClass: Can't open file: " << fname; return nullptr; } FstHeader hdr; if (!hdr.Read(istrm, fname)) return nullptr; const FstReadOptions read_options(fname, &hdr); const auto &arc_type = hdr.ArcType(); static const auto *io_register = IORegistration<F>::Register::GetRegister(); const auto reader = io_register->GetReader(arc_type); if (!reader) { LOG(ERROR) << "ReadFstClass: Unknown arc type: " << arc_type; return nullptr; } return reader(istrm, read_options); } template <class F> FstClassImplBase *CreateFstClass(const string &arc_type) { static const auto *io_register = IORegistration<F>::Register::GetRegister(); auto creator = io_register->GetCreator(arc_type); if (!creator) { FSTERROR() << "CreateFstClass: Unknown arc type: " << arc_type; return nullptr; } return creator(); } template <class F> FstClassImplBase *ConvertFstClass(const FstClass &other) { static const auto *io_register = IORegistration<F>::Register::GetRegister(); auto converter = io_register->GetConverter(other.ArcType()); if (!converter) { FSTERROR() << "ConvertFstClass: Unknown arc type: " << other.ArcType(); return nullptr; } return converter(other); } } // namespace // FstClass methods. FstClass *FstClass::Read(const string &fname) { if (!fname.empty()) { std::ifstream istrm(fname, std::ios_base::in | std::ios_base::binary); return ReadFstClass<FstClass>(istrm, fname); } else { return ReadFstClass<FstClass>(std::cin, "standard input"); } } FstClass *FstClass::Read(std::istream &istrm, const string &source) { return ReadFstClass<FstClass>(istrm, source); } bool FstClass::WeightTypesMatch(const WeightClass &weight, const string &op_name) const { if (WeightType() != weight.Type()) { FSTERROR() << "FST and weight with non-matching weight types passed to " << op_name << ": " << WeightType() << " and " << weight.Type(); return false; } return true; } // MutableFstClass methods. MutableFstClass *MutableFstClass::Read(const string &fname, bool convert) { if (convert == false) { if (!fname.empty()) { std::ifstream in(fname, std::ios_base::in | std::ios_base::binary); return ReadFstClass<MutableFstClass>(in, fname); } else { return ReadFstClass<MutableFstClass>(std::cin, "standard input"); } } else { // Converts to VectorFstClass if not mutable. std::unique_ptr<FstClass> ifst(FstClass::Read(fname)); if (!ifst) return nullptr; if (ifst->Properties(kMutable, false) == kMutable) { return static_cast<MutableFstClass *>(ifst.release()); } else { return new VectorFstClass(*ifst.release()); } } } // VectorFstClass methods. VectorFstClass *VectorFstClass::Read(const string &fname) { if (!fname.empty()) { std::ifstream in(fname, std::ios_base::in | std::ios_base::binary); return ReadFstClass<VectorFstClass>(in, fname); } else { return ReadFstClass<VectorFstClass>(std::cin, "standard input"); } } VectorFstClass::VectorFstClass(const string &arc_type) : MutableFstClass(CreateFstClass<VectorFstClass>(arc_type)) {} VectorFstClass::VectorFstClass(const FstClass &other) : MutableFstClass(ConvertFstClass<VectorFstClass>(other)) {} } // namespace script } // namespace fst
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/script/draw.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <ostream> #include <string> #include <fst/script/draw.h> #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> namespace fst { namespace script { void DrawFst(const FstClass &fst, const SymbolTable *isyms, const SymbolTable *osyms, const SymbolTable *ssyms, bool accep, const string &title, float width, float height, bool portrait, bool vertical, float ranksep, float nodesep, int fontsize, int precision, const string &float_format, bool show_weight_one, std::ostream *ostrm, const string &dest) { FstDrawerArgs args(fst, isyms, osyms, ssyms, accep, title, width, height, portrait, vertical, ranksep, nodesep, fontsize, precision, float_format, show_weight_one, ostrm, dest); Apply<Operation<FstDrawerArgs>>("DrawFst", fst.ArcType(), &args); } REGISTER_FST_OPERATION(DrawFst, StdArc, FstDrawerArgs); REGISTER_FST_OPERATION(DrawFst, LogArc, FstDrawerArgs); REGISTER_FST_OPERATION(DrawFst, Log64Arc, FstDrawerArgs); } // namespace script } // namespace fst
0
coqui_public_repos/coqpit
coqui_public_repos/coqpit/tests/test_copying.py
import copy from dataclasses import dataclass from coqpit.coqpit import Coqpit @dataclass class SimpleConfig(Coqpit): val_a: int = 10 def test_copying(): config = SimpleConfig() config_new = config.copy() config_new.val_a = 1234 assert config.val_a != config_new.val_a config_new = copy.copy(config) config_new.val_a = 4321 assert config.val_a != config_new.val_a config_new = copy.deepcopy(config) config_new.val_a = 4321 assert config.val_a != config_new.val_a
0
coqui_public_repos/TTS/docs/source
coqui_public_repos/TTS/docs/source/models/bark.md
# 🐶 Bark Bark is a multi-lingual TTS model created by [Suno-AI](https://www.suno.ai/). It can generate conversational speech as well as music and sound effects. It is architecturally very similar to Google's [AudioLM](https://arxiv.org/abs/2209.03143). For more information, please refer to the [Suno-AI's repo](https://github.com/suno-ai/bark). ## Acknowledgements - 👑[Suno-AI](https://www.suno.ai/) for training and open-sourcing this model. - 👑[gitmylo](https://github.com/gitmylo) for finding [the solution](https://github.com/gitmylo/bark-voice-cloning-HuBERT-quantizer/) to the semantic token generation for voice clones and finetunes. - 👑[serp-ai](https://github.com/serp-ai/bark-with-voice-clone) for controlled voice cloning. ## Example Use ```python text = "Hello, my name is Manmay , how are you?" from TTS.tts.configs.bark_config import BarkConfig from TTS.tts.models.bark import Bark config = BarkConfig() model = Bark.init_from_config(config) model.load_checkpoint(config, checkpoint_dir="path/to/model/dir/", eval=True) # with random speaker output_dict = model.synthesize(text, config, speaker_id="random", voice_dirs=None) # cloning a speaker. # It assumes that you have a speaker file in `bark_voices/speaker_n/speaker.wav` or `bark_voices/speaker_n/speaker.npz` output_dict = model.synthesize(text, config, speaker_id="ljspeech", voice_dirs="bark_voices/") ``` Using 🐸TTS API: ```python from TTS.api import TTS # Load the model to GPU # Bark is really slow on CPU, so we recommend using GPU. tts = TTS("tts_models/multilingual/multi-dataset/bark", gpu=True) # Cloning a new speaker # This expects to find a mp3 or wav file like `bark_voices/new_speaker/speaker.wav` # It computes the cloning values and stores in `bark_voices/new_speaker/speaker.npz` tts.tts_to_file(text="Hello, my name is Manmay , how are you?", file_path="output.wav", voice_dir="bark_voices/", speaker="ljspeech") # When you run it again it uses the stored values to generate the voice. tts.tts_to_file(text="Hello, my name is Manmay , how are you?", file_path="output.wav", voice_dir="bark_voices/", speaker="ljspeech") # random speaker tts = TTS("tts_models/multilingual/multi-dataset/bark", gpu=True) tts.tts_to_file("hello world", file_path="out.wav") ``` Using 🐸TTS Command line: ```console # cloning the `ljspeech` voice tts --model_name tts_models/multilingual/multi-dataset/bark \ --text "This is an example." \ --out_path "output.wav" \ --voice_dir bark_voices/ \ --speaker_idx "ljspeech" \ --progress_bar True # Random voice generation tts --model_name tts_models/multilingual/multi-dataset/bark \ --text "This is an example." \ --out_path "output.wav" \ --progress_bar True ``` ## Important resources & papers - Original Repo: https://github.com/suno-ai/bark - Cloning implementation: https://github.com/serp-ai/bark-with-voice-clone - AudioLM: https://arxiv.org/abs/2209.03143 ## BarkConfig ```{eval-rst} .. autoclass:: TTS.tts.configs.bark_config.BarkConfig :members: ``` ## Bark Model ```{eval-rst} .. autoclass:: TTS.tts.models.bark.Bark :members: ```
0
coqui_public_repos
coqui_public_repos/STT/requirements_eval_tflite.txt
absl-py==0.9.0 attrdict==2.0.1 stt numpy==1.16.0 progressbar2==3.47.0 python-utils==2.3.0 six==1.13.0 pandas==0.25.3
0
coqui_public_repos/STT-examples
coqui_public_repos/STT-examples/electron/package.json
{ "name": "STT-electron", "productName": "STT-electron", "version": "1.0.0", "description": "My Electron application description", "main": "public/electron.js", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "dev": "concurrently \"BROWSER=none npm start\" \"wait-on http://localhost:3000 && electron --inspect=5858 .\"", "dev-win": "concurrently \"npm start\" \"wait-on http://localhost:3000 && electron --inspect=5858 .\"", "rebuild": "npm rebuild --runtime=electron --target=9.0.5 --disturl=https://atom.io/download/atom-shell --abi=75", "pack": "npm run build && electron-builder --dir", "dist": "npm run build && electron-builder", "dist-win": "npm run build && electron-builder --x64", "dev-test": "concurrently --kill-others --success first \"wait-on http://localhost:3000 && ./node_modules/.bin/electron public/electron.js STT_TEST\" \"BROWSER=none npm start\"" }, "postinstall": "electron-builder install-app-deps", "homepage": "./", "build": { "appId": "STT-electron", "productName": "STT-electron", "files": [ "build/**/*", "node_modules/**/*", "package.json" ], "buildDependenciesFromSource": true, "artifactName": "STT-electron-${version}-${os}-${arch}.${ext}", "dmg": { "title": "${productName}" }, "mac": { "category": "public.app-category.utilities", "target": [ { "target": "dmg", "arch": [ "x64" ] }, { "target": "zip", "arch": [ "x64" ] } ], "identity": null }, "win": { "target": "nsis", "artifactName": "STT-electron-${version}-${os}-${arch}.${ext}" }, "linux": { "target": [ { "target": "AppImage" } ], "category": "Utility" } }, "keywords": [], "license": "MIT", "dependencies": { "STT": "^1.0.0", "electron-is-dev": "^1.1.0", "lodash": "^4.17.15", "node-abi": "^2.18.0", "react": "^16.12.0", "react-dom": "^16.12.0", "react-scripts": "^3.4.1", "request": "^2.88.2", "wav": "^1.0.2" }, "devDependencies": { "concurrently": "^5.0.0", "electron": "9.0.5", "electron-builder": "^22.7.0", "electron-rebuild": "^1.11.0", "wait-on": "^3.3.0" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
0
coqui_public_repos/inference-engine/third_party/kenlm/lm
coqui_public_repos/inference-engine/third_party/kenlm/lm/common/size_option.hh
#include <boost/program_options.hpp> #include <cstddef> #include <string> namespace lm { // Create a boost program option for data sizes. This parses sizes like 1T and 10k. boost::program_options::typed_value<std::string> *SizeOption(std::size_t &to, const char *default_value); } // namespace lm
0
coqui_public_repos/inference-engine/third_party/kenlm/lm/common
coqui_public_repos/inference-engine/third_party/kenlm/lm/common/test_data/toy1.arpa
\data\ ngram 1=6 ngram 2=7 ngram 3=6 \1-grams: -1 <unk> 0 0 <s> -0.30103 -0.6146491 a -0.30103 -0.6146491 </s> 0 -0.7659168 c -0.30103 -0.6146491 b -0.30103 \2-grams: -0.4301247 <s> a -0.30103 -0.4301247 a a -0.30103 -0.20660876 c </s> 0 -0.5404639 b </s> 0 -0.4740302 <s> c -0.30103 -0.4301247 a b -0.30103 -0.3422159 b b -0.47712123 \3-grams: -0.1638568 <s> a a -0.09113217 <s> c </s> -0.7462621 b b </s> -0.1638568 a a b -0.13823806 a b b -0.13375957 b b b \end\
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-cpp-linux-amd64-prod_pbmodel-opt.yml
build: template_file: test-linux-opt-base.tyml dependencies: - "linux-amd64-cpu-opt" args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-cpp-ds-tests-prod.sh 16k" workerType: "${docker.dsTests}" metadata: name: "DeepSpeech Linux AMD64 CPU C++ prod tests" description: "Testing DeepSpeech C++ for Linux/AMD64 on prod model, CPU only, optimized version"
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/concat.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Functions and classes to compute the concatenation of two FSTs. #ifndef FST_CONCAT_H_ #define FST_CONCAT_H_ #include <algorithm> #include <vector> #include <fst/mutable-fst.h> #include <fst/rational.h> namespace fst { // Computes the concatenation (product) of two FSTs. If FST1 transduces string // x to y with weight a and FST2 transduces string w to v with weight b, then // their concatenation transduces string xw to yv with weight Times(a, b). // // This version modifies its MutableFst argument (in first position). // // Complexity: // // Time: O(V1 + V2 + E2) // Space: O(V1 + V2 + E2) // // where Vi is the number of states, and Ei is the number of arcs, of the ith // FST. template <class Arc> void Concat(MutableFst<Arc> *fst1, const Fst<Arc> &fst2) { using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; // Checks that the symbol table are compatible. if (!CompatSymbols(fst1->InputSymbols(), fst2.InputSymbols()) || !CompatSymbols(fst1->OutputSymbols(), fst2.OutputSymbols())) { FSTERROR() << "Concat: Input/output symbol tables of 1st argument " << "does not match input/output symbol tables of 2nd argument"; fst1->SetProperties(kError, kError); return; } const auto props1 = fst1->Properties(kFstProperties, false); const auto props2 = fst2.Properties(kFstProperties, false); const auto start1 = fst1->Start(); if (start1 == kNoStateId) { if (props2 & kError) fst1->SetProperties(kError, kError); return; } const auto numstates1 = fst1->NumStates(); if (fst2.Properties(kExpanded, false)) { fst1->ReserveStates(numstates1 + CountStates(fst2)); } for (StateIterator<Fst<Arc>> siter2(fst2); !siter2.Done(); siter2.Next()) { const auto s1 = fst1->AddState(); const auto s2 = siter2.Value(); fst1->SetFinal(s1, fst2.Final(s2)); fst1->ReserveArcs(s1, fst2.NumArcs(s2)); for (ArcIterator<Fst<Arc>> aiter(fst2, s2); !aiter.Done(); aiter.Next()) { auto arc = aiter.Value(); arc.nextstate += numstates1; fst1->AddArc(s1, arc); } } const auto start2 = fst2.Start(); for (StateId s1 = 0; s1 < numstates1; ++s1) { const auto weight = fst1->Final(s1); if (weight != Weight::Zero()) { fst1->SetFinal(s1, Weight::Zero()); if (start2 != kNoStateId) { fst1->AddArc(s1, Arc(0, 0, weight, start2 + numstates1)); } } } if (start2 != kNoStateId) { fst1->SetProperties(ConcatProperties(props1, props2), kFstProperties); } } // Computes the concatentation of two FSTs. This version modifies its // MutableFst argument (in second position). // // Complexity: // // Time: O(V1 + E1) // Space: O(V1 + E1) // // where Vi is the number of states, and Ei is the number of arcs, of the ith // FST. template <class Arc> void Concat(const Fst<Arc> &fst1, MutableFst<Arc> *fst2) { using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; // Checks that the symbol table are compatible. if (!CompatSymbols(fst1.InputSymbols(), fst2->InputSymbols()) || !CompatSymbols(fst1.OutputSymbols(), fst2->OutputSymbols())) { FSTERROR() << "Concat: Input/output symbol tables of 1st argument " << "does not match input/output symbol tables of 2nd argument"; fst2->SetProperties(kError, kError); return; } const auto props1 = fst1.Properties(kFstProperties, false); const auto props2 = fst2->Properties(kFstProperties, false); const auto start2 = fst2->Start(); if (start2 == kNoStateId) { if (props1 & kError) fst2->SetProperties(kError, kError); return; } const auto numstates2 = fst2->NumStates(); if (fst1.Properties(kExpanded, false)) { fst2->ReserveStates(numstates2 + CountStates(fst1)); } for (StateIterator<Fst<Arc>> siter(fst1); !siter.Done(); siter.Next()) { const auto s1 = siter.Value(); const auto s2 = fst2->AddState(); const auto weight = fst1.Final(s1); if (weight != Weight::Zero()) { fst2->ReserveArcs(s2, fst1.NumArcs(s1) + 1); fst2->AddArc(s2, Arc(0, 0, weight, start2)); } else { fst2->ReserveArcs(s2, fst1.NumArcs(s1)); } for (ArcIterator<Fst<Arc>> aiter(fst1, s1); !aiter.Done(); aiter.Next()) { auto arc = aiter.Value(); arc.nextstate += numstates2; fst2->AddArc(s2, arc); } } const auto start1 = fst1.Start(); if (start1 != kNoStateId) { fst2->SetStart(start1 + numstates2); fst2->SetProperties(ConcatProperties(props1, props2), kFstProperties); } else { fst2->SetStart(fst2->AddState()); } } // Computes the concatentation of two FSTs. This version modifies its // RationalFst input (in first position). template <class Arc> void Concat(RationalFst<Arc> *fst1, const Fst<Arc> &fst2) { fst1->GetMutableImpl()->AddConcat(fst2, true); } // Computes the concatentation of two FSTs. This version modifies its // RationalFst input (in second position). template <class Arc> void Concat(const Fst<Arc> &fst1, RationalFst<Arc> *fst2) { fst2->GetMutableImpl()->AddConcat(fst1, false); } using ConcatFstOptions = RationalFstOptions; // Computes the concatenation (product) of two FSTs; this version is a delayed // FST. If FST1 transduces string x to y with weight a and FST2 transduces // string w to v with weight b, then their concatenation transduces string xw // to yv with Times(a, b). // // Complexity: // // Time: O(v1 + e1 + v2 + e2), // Space: O(v1 + v2) // // where vi is the number of states visited, and ei is the number of arcs // visited, of the ith FST. Constant time and space to visit an input state or // arc is assumed and exclusive of caching. template <class A> class ConcatFst : public RationalFst<A> { public: using Arc = A; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; ConcatFst(const Fst<Arc> &fst1, const Fst<Arc> &fst2) { GetMutableImpl()->InitConcat(fst1, fst2); } ConcatFst(const Fst<Arc> &fst1, const Fst<Arc> &fst2, const ConcatFstOptions &opts) : RationalFst<Arc>(opts) { GetMutableImpl()->InitConcat(fst1, fst2); } // See Fst<>::Copy() for doc. ConcatFst(const ConcatFst<Arc> &fst, bool safe = false) : RationalFst<Arc>(fst, safe) {} // Get a copy of this ConcatFst. See Fst<>::Copy() for further doc. ConcatFst<Arc> *Copy(bool safe = false) const override { return new ConcatFst<Arc>(*this, safe); } private: using ImplToFst<internal::RationalFstImpl<Arc>>::GetImpl; using ImplToFst<internal::RationalFstImpl<Arc>>::GetMutableImpl; }; // Specialization for ConcatFst. template <class Arc> class StateIterator<ConcatFst<Arc>> : public StateIterator<RationalFst<Arc>> { public: explicit StateIterator(const ConcatFst<Arc> &fst) : StateIterator<RationalFst<Arc>>(fst) {} }; // Specialization for ConcatFst. template <class Arc> class ArcIterator<ConcatFst<Arc>> : public ArcIterator<RationalFst<Arc>> { public: using StateId = typename Arc::StateId; ArcIterator(const ConcatFst<Arc> &fst, StateId s) : ArcIterator<RationalFst<Arc>>(fst, s) {} }; // Useful alias when using StdArc. using StdConcatFst = ConcatFst<StdArc>; } // namespace fst #endif // FST_CONCAT_H_
0
coqui_public_repos/TTS/TTS
coqui_public_repos/TTS/TTS/utils/download.py
# Adapted from https://github.com/pytorch/audio/ import hashlib import logging import os import tarfile import urllib import urllib.request import zipfile from os.path import expanduser from typing import Any, Iterable, List, Optional from torch.utils.model_zoo import tqdm def stream_url( url: str, start_byte: Optional[int] = None, block_size: int = 32 * 1024, progress_bar: bool = True ) -> Iterable: """Stream url by chunk Args: url (str): Url. start_byte (int or None, optional): Start streaming at that point (Default: ``None``). block_size (int, optional): Size of chunks to stream (Default: ``32 * 1024``). progress_bar (bool, optional): Display a progress bar (Default: ``True``). """ # If we already have the whole file, there is no need to download it again req = urllib.request.Request(url, method="HEAD") with urllib.request.urlopen(req) as response: url_size = int(response.info().get("Content-Length", -1)) if url_size == start_byte: return req = urllib.request.Request(url) if start_byte: req.headers["Range"] = "bytes={}-".format(start_byte) with urllib.request.urlopen(req) as upointer, tqdm( unit="B", unit_scale=True, unit_divisor=1024, total=url_size, disable=not progress_bar, ) as pbar: num_bytes = 0 while True: chunk = upointer.read(block_size) if not chunk: break yield chunk num_bytes += len(chunk) pbar.update(len(chunk)) def download_url( url: str, download_folder: str, filename: Optional[str] = None, hash_value: Optional[str] = None, hash_type: str = "sha256", progress_bar: bool = True, resume: bool = False, ) -> None: """Download file to disk. Args: url (str): Url. download_folder (str): Folder to download file. filename (str or None, optional): Name of downloaded file. If None, it is inferred from the url (Default: ``None``). hash_value (str or None, optional): Hash for url (Default: ``None``). hash_type (str, optional): Hash type, among "sha256" and "md5" (Default: ``"sha256"``). progress_bar (bool, optional): Display a progress bar (Default: ``True``). resume (bool, optional): Enable resuming download (Default: ``False``). """ req = urllib.request.Request(url, method="HEAD") req_info = urllib.request.urlopen(req).info() # pylint: disable=consider-using-with # Detect filename filename = filename or req_info.get_filename() or os.path.basename(url) filepath = os.path.join(download_folder, filename) if resume and os.path.exists(filepath): mode = "ab" local_size: Optional[int] = os.path.getsize(filepath) elif not resume and os.path.exists(filepath): raise RuntimeError("{} already exists. Delete the file manually and retry.".format(filepath)) else: mode = "wb" local_size = None if hash_value and local_size == int(req_info.get("Content-Length", -1)): with open(filepath, "rb") as file_obj: if validate_file(file_obj, hash_value, hash_type): return raise RuntimeError("The hash of {} does not match. Delete the file manually and retry.".format(filepath)) with open(filepath, mode) as fpointer: for chunk in stream_url(url, start_byte=local_size, progress_bar=progress_bar): fpointer.write(chunk) with open(filepath, "rb") as file_obj: if hash_value and not validate_file(file_obj, hash_value, hash_type): raise RuntimeError("The hash of {} does not match. Delete the file manually and retry.".format(filepath)) def validate_file(file_obj: Any, hash_value: str, hash_type: str = "sha256") -> bool: """Validate a given file object with its hash. Args: file_obj: File object to read from. hash_value (str): Hash for url. hash_type (str, optional): Hash type, among "sha256" and "md5" (Default: ``"sha256"``). Returns: bool: return True if its a valid file, else False. """ if hash_type == "sha256": hash_func = hashlib.sha256() elif hash_type == "md5": hash_func = hashlib.md5() else: raise ValueError while True: # Read by chunk to avoid filling memory chunk = file_obj.read(1024**2) if not chunk: break hash_func.update(chunk) return hash_func.hexdigest() == hash_value def extract_archive(from_path: str, to_path: Optional[str] = None, overwrite: bool = False) -> List[str]: """Extract archive. Args: from_path (str): the path of the archive. to_path (str or None, optional): the root path of the extraced files (directory of from_path) (Default: ``None``) overwrite (bool, optional): overwrite existing files (Default: ``False``) Returns: list: List of paths to extracted files even if not overwritten. """ if to_path is None: to_path = os.path.dirname(from_path) try: with tarfile.open(from_path, "r") as tar: logging.info("Opened tar file %s.", from_path) files = [] for file_ in tar: # type: Any file_path = os.path.join(to_path, file_.name) if file_.isfile(): files.append(file_path) if os.path.exists(file_path): logging.info("%s already extracted.", file_path) if not overwrite: continue tar.extract(file_, to_path) return files except tarfile.ReadError: pass try: with zipfile.ZipFile(from_path, "r") as zfile: logging.info("Opened zip file %s.", from_path) files = zfile.namelist() for file_ in files: file_path = os.path.join(to_path, file_) if os.path.exists(file_path): logging.info("%s already extracted.", file_path) if not overwrite: continue zfile.extract(file_, to_path) return files except zipfile.BadZipFile: pass raise NotImplementedError(" > [!] only supports tar.gz, tgz, and zip achives.") def download_kaggle_dataset(dataset_path: str, dataset_name: str, output_path: str): """Download dataset from kaggle. Args: dataset_path (str): This the kaggle link to the dataset. for example vctk is 'mfekadu/english-multispeaker-corpus-for-voice-cloning' dataset_name (str): Name of the folder the dataset will be saved in. output_path (str): Path of the location you want the dataset folder to be saved to. """ data_path = os.path.join(output_path, dataset_name) try: import kaggle # pylint: disable=import-outside-toplevel kaggle.api.authenticate() print(f"""\nDownloading {dataset_name}...""") kaggle.api.dataset_download_files(dataset_path, path=data_path, unzip=True) except OSError: print( f"""[!] in order to download kaggle datasets, you need to have a kaggle api token stored in your {os.path.join(expanduser('~'), '.kaggle/kaggle.json')}""" )
0
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/session/experimental_onnxruntime_cxx_api.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Summary: The experimental Ort C++ API is a wrapper around the Ort C++ API. // // This C++ API further simplifies usage and provides support for modern C++ syntax/features // at the cost of some overhead (i.e. using std::string over char *). // // Where applicable, default memory allocator options are used unless explicitly set. // // Experimental components are designed as drop-in replacements of the regular API, requiring // minimal code modifications to use. // // Example: Ort::Session -> Ort::Experimental::Session // // NOTE: Experimental API components are subject to change based on feedback and provide no // guarantee of backwards compatibility in future releases. #pragma once #include "onnxruntime_cxx_api.h" namespace Ort { namespace Experimental { struct Session : Ort::Session { Session(Env& env, std::basic_string<ORTCHAR_T>& model_path, SessionOptions& options) : Ort::Session(env, model_path.data(), options){}; Session(Env& env, void* model_data, size_t model_data_length, SessionOptions& options) : Ort::Session(env, model_data, model_data_length, options){}; // overloaded Run() with sensible defaults std::vector<Ort::Value> Run(const std::vector<std::string>& input_names, const std::vector<Ort::Value>& input_values, const std::vector<std::string>& output_names, const RunOptions& run_options = RunOptions()); void Run(const std::vector<std::string>& input_names, const std::vector<Ort::Value>& input_values, const std::vector<std::string>& output_names, std::vector<Ort::Value>& output_values, const RunOptions& run_options = RunOptions()); // convenience methods that simplify common lower-level API calls std::vector<std::string> GetInputNames() const; std::vector<std::string> GetOutputNames() const; std::vector<std::string> GetOverridableInitializerNames() const; // NOTE: shape dimensions may have a negative value to indicate a symbolic/unknown dimension. std::vector<std::vector<int64_t> > GetInputShapes() const; std::vector<std::vector<int64_t> > GetOutputShapes() const; std::vector<std::vector<int64_t> > GetOverridableInitializerShapes() const; }; struct Value : Ort::Value { Value(OrtValue* p) : Ort::Value(p){}; template <typename T> static Ort::Value CreateTensor(T* p_data, size_t p_data_element_count, const std::vector<int64_t>& shape); static Ort::Value CreateTensor(void* p_data, size_t p_data_byte_count, const std::vector<int64_t>& shape, ONNXTensorElementDataType type); template <typename T> static Ort::Value CreateTensor(const std::vector<int64_t>& shape); static Ort::Value CreateTensor(const std::vector<int64_t>& shape, ONNXTensorElementDataType type); }; } } #include "experimental_onnxruntime_cxx_inline.h"
0
coqui_public_repos/inference-engine/third_party
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/INSTALL
Installation Instructions ************************* Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. This file is free documentation; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. Basic Installation ================== Briefly, the shell commands `./configure; make; make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package. 4. Type `make install' to install the programs and any data files and documentation. 5. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 6. Often, you can also type `make uninstall' to remove the installed files again. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX'. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Optional Features ================= Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf bug. Until the bug is fixed you can use this workaround: CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of the options to `configure', and exit. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details.
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/project.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Functions and classes to project an FST on to its domain or range. #ifndef FST_PROJECT_H_ #define FST_PROJECT_H_ #include <fst/arc-map.h> #include <fst/mutable-fst.h> namespace fst { // This specifies whether to project on input or output. enum ProjectType { PROJECT_INPUT = 1, PROJECT_OUTPUT = 2 }; // Mapper to implement projection per arc. template <class A> class ProjectMapper { public: using FromArc = A; using ToArc = A; explicit ProjectMapper(ProjectType project_type) : project_type_(project_type) {} ToArc operator()(const FromArc &arc) const { const auto label = project_type_ == PROJECT_INPUT ? arc.ilabel : arc.olabel; return ToArc(label, label, arc.weight, arc.nextstate); } constexpr MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; } MapSymbolsAction InputSymbolsAction() const { return project_type_ == PROJECT_INPUT ? MAP_COPY_SYMBOLS : MAP_CLEAR_SYMBOLS; } MapSymbolsAction OutputSymbolsAction() const { return project_type_ == PROJECT_OUTPUT ? MAP_COPY_SYMBOLS : MAP_CLEAR_SYMBOLS; } uint64_t Properties(uint64_t props) const { return ProjectProperties(props, project_type_ == PROJECT_INPUT); } private: const ProjectType project_type_; }; // Projects an FST onto its domain or range by either copying each arcs' input // label to the output label or vice versa. // // Complexity: // // Time: O(V + E) // Space: O(1) // // where V is the number of states and E is the number of arcs. template <class Arc> inline void Project(const Fst<Arc> &ifst, MutableFst<Arc> *ofst, ProjectType project_type) { ArcMap(ifst, ofst, ProjectMapper<Arc>(project_type)); switch (project_type) { case PROJECT_INPUT: ofst->SetOutputSymbols(ifst.InputSymbols()); return; case PROJECT_OUTPUT: ofst->SetInputSymbols(ifst.OutputSymbols()); return; } } // Destructive variant of the above. template <class Arc> inline void Project(MutableFst<Arc> *fst, ProjectType project_type) { ArcMap(fst, ProjectMapper<Arc>(project_type)); switch (project_type) { case PROJECT_INPUT: fst->SetOutputSymbols(fst->InputSymbols()); return; case PROJECT_OUTPUT: fst->SetInputSymbols(fst->OutputSymbols()); return; } } // Projects an FST onto its domain or range by either copying each arc's input // label to the output label or vice versa. This version is a delayed FST. // // Complexity: // // Time: O(v + e) // Space: O(1) // // where v is the number of states visited and e is the number of arcs visited. // Constant time and to visit an input state or arc is assumed and exclusive of // caching. template <class A> class ProjectFst : public ArcMapFst<A, A, ProjectMapper<A>> { public: using FromArc = A; using ToArc = A; using Impl = internal::ArcMapFstImpl<A, A, ProjectMapper<A>>; ProjectFst(const Fst<A> &fst, ProjectType project_type) : ArcMapFst<A, A, ProjectMapper<A>>(fst, ProjectMapper<A>(project_type)) { if (project_type == PROJECT_INPUT) { GetMutableImpl()->SetOutputSymbols(fst.InputSymbols()); } if (project_type == PROJECT_OUTPUT) { GetMutableImpl()->SetInputSymbols(fst.OutputSymbols()); } } // See Fst<>::Copy() for doc. ProjectFst(const ProjectFst<A> &fst, bool safe = false) : ArcMapFst<A, A, ProjectMapper<A>>(fst, safe) {} // Gets a copy of this ProjectFst. See Fst<>::Copy() for further doc. ProjectFst<A> *Copy(bool safe = false) const override { return new ProjectFst(*this, safe); } private: using ImplToFst<Impl>::GetMutableImpl; }; // Specialization for ProjectFst. template <class A> class StateIterator<ProjectFst<A>> : public StateIterator<ArcMapFst<A, A, ProjectMapper<A>>> { public: explicit StateIterator(const ProjectFst<A> &fst) : StateIterator<ArcMapFst<A, A, ProjectMapper<A>>>(fst) {} }; // Specialization for ProjectFst. template <class A> class ArcIterator<ProjectFst<A>> : public ArcIterator<ArcMapFst<A, A, ProjectMapper<A>>> { public: using StateId = typename A::StateId; ArcIterator(const ProjectFst<A> &fst, StateId s) : ArcIterator<ArcMapFst<A, A, ProjectMapper<A>>>(fst, s) {} }; // Useful alias when using StdArc. using StdProjectFst = ProjectFst<StdArc>; } // namespace fst #endif // FST_PROJECT_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstreverse.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/flags.h> DEFINE_bool(require_superinitial, true, "Always create a superinitial state"); int fstreverse_main(int argc, char **argv); int main(int argc, char **argv) { return fstreverse_main(argc, argv); }
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-nodejs_15x-darwin-amd64-opt.yml
build: template_file: test-darwin-opt-base.tyml dependencies: - "darwin-amd64-cpu-opt" - "test-training_16k-linux-amd64-py36m-opt" - "homebrew_tests-darwin-amd64" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${nodejs.brew.prep_15} args: tests_cmdline: "$TASKCLUSTER_TASK_DIR/DeepSpeech/ds/taskcluster/tc-node-tests.sh 15.x 16k" metadata: name: "DeepSpeech OSX AMD64 CPU NodeJS 15.x tests" description: "Testing DeepSpeech for OSX/AMD64 on NodeJS v15.x, CPU only, optimized version"
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/android-arm64-cpu-opt.yml
build: template_file: linux-opt-base.tyml dependencies: - "swig-linux-amd64" - "node-gyp-cache" - "pyenv-linux-amd64" - "tf_android-arm64-opt" routes: - "index.project.deepspeech.deepspeech.native_client.${event.head.branchortag}.android-arm64" - "index.project.deepspeech.deepspeech.native_client.${event.head.branchortag}.${event.head.sha}.android-arm64" - "index.project.deepspeech.deepspeech.native_client.android-arm64.${event.head.sha}" tensorflow: ${system.tensorflow.android_arm64.url} scripts: setup: "taskcluster/tc-true.sh" build: "taskcluster/android-build.sh arm64-v8a" package: "taskcluster/android-package.sh arm64-v8a" nc_asset_name: "native_client.arm64.cpu.android.tar.xz" workerType: "${docker.dsBuild}" metadata: name: "DeepSpeech Android ARM64" description: "Building DeepSpeech for Android ARM64, optimized version"
0
coqui_public_repos/inference-engine/third_party/kenlm/lm
coqui_public_repos/inference-engine/third_party/kenlm/lm/common/compare.hh
#ifndef LM_COMMON_COMPARE_H #define LM_COMMON_COMPARE_H #include "lm/common/ngram.hh" #include "lm/word_index.hh" #include <functional> #include <string> namespace lm { /** * Abstract parent class for defining custom n-gram comparators. */ template <class Child> class Comparator : public std::binary_function<const void *, const void *, bool> { public: /** * Constructs a comparator capable of comparing two n-grams. * * @param order Number of words in each n-gram */ explicit Comparator(std::size_t order) : order_(order) {} /** * Applies the comparator using the Compare method that must be defined in any class that inherits from this class. * * @param lhs A pointer to the n-gram on the left-hand side of the comparison * @param rhs A pointer to the n-gram on the right-hand side of the comparison * * @see ContextOrder::Compare * @see PrefixOrder::Compare * @see SuffixOrder::Compare */ inline bool operator()(const void *lhs, const void *rhs) const { return static_cast<const Child*>(this)->Compare(static_cast<const WordIndex*>(lhs), static_cast<const WordIndex*>(rhs)); } /** Gets the n-gram order defined for this comparator. */ std::size_t Order() const { return order_; } protected: std::size_t order_; }; /** * N-gram comparator that compares n-grams according to their reverse (suffix) order. * * This comparator compares n-grams lexicographically, one word at a time, * beginning with the last word of each n-gram and ending with the first word of each n-gram. * * Some examples of n-gram comparisons as defined by this comparator: * - a b c == a b c * - a b c < a b d * - a b c > a d b * - a b c > a b b * - a b c > x a c * - a b c < x y z */ class SuffixOrder : public Comparator<SuffixOrder> { public: /** * Constructs a comparator capable of comparing two n-grams. * * @param order Number of words in each n-gram */ explicit SuffixOrder(std::size_t order) : Comparator<SuffixOrder>(order) {} /** * Compares two n-grams lexicographically, one word at a time, * beginning with the last word of each n-gram and ending with the first word of each n-gram. * * @param lhs A pointer to the n-gram on the left-hand side of the comparison * @param rhs A pointer to the n-gram on the right-hand side of the comparison */ inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const { for (std::size_t i = order_ - 1; i != 0; --i) { if (lhs[i] != rhs[i]) return lhs[i] < rhs[i]; } return lhs[0] < rhs[0]; } static const unsigned kMatchOffset = 1; }; /** * N-gram comparator that compares n-grams according to the reverse (suffix) order of the n-gram context. * * This comparator compares n-grams lexicographically, one word at a time, * beginning with the penultimate word of each n-gram and ending with the first word of each n-gram; * finally, this comparator compares the last word of each n-gram. * * Some examples of n-gram comparisons as defined by this comparator: * - a b c == a b c * - a b c < a b d * - a b c < a d b * - a b c > a b b * - a b c > x a c * - a b c < x y z */ class ContextOrder : public Comparator<ContextOrder> { public: /** * Constructs a comparator capable of comparing two n-grams. * * @param order Number of words in each n-gram */ explicit ContextOrder(std::size_t order) : Comparator<ContextOrder>(order) {} /** * Compares two n-grams lexicographically, one word at a time, * beginning with the penultimate word of each n-gram and ending with the first word of each n-gram; * finally, this comparator compares the last word of each n-gram. * * @param lhs A pointer to the n-gram on the left-hand side of the comparison * @param rhs A pointer to the n-gram on the right-hand side of the comparison */ inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const { for (int i = order_ - 2; i >= 0; --i) { if (lhs[i] != rhs[i]) return lhs[i] < rhs[i]; } return lhs[order_ - 1] < rhs[order_ - 1]; } }; /** * N-gram comparator that compares n-grams according to their natural (prefix) order. * * This comparator compares n-grams lexicographically, one word at a time, * beginning with the first word of each n-gram and ending with the last word of each n-gram. * * Some examples of n-gram comparisons as defined by this comparator: * - a b c == a b c * - a b c < a b d * - a b c < a d b * - a b c > a b b * - a b c < x a c * - a b c < x y z */ class PrefixOrder : public Comparator<PrefixOrder> { public: /** * Constructs a comparator capable of comparing two n-grams. * * @param order Number of words in each n-gram */ explicit PrefixOrder(std::size_t order) : Comparator<PrefixOrder>(order) {} /** * Compares two n-grams lexicographically, one word at a time, * beginning with the first word of each n-gram and ending with the last word of each n-gram. * * @param lhs A pointer to the n-gram on the left-hand side of the comparison * @param rhs A pointer to the n-gram on the right-hand side of the comparison */ inline bool Compare(const WordIndex *lhs, const WordIndex *rhs) const { for (std::size_t i = 0; i < order_; ++i) { if (lhs[i] != rhs[i]) return lhs[i] < rhs[i]; } return false; } static const unsigned kMatchOffset = 0; }; template <class Range> struct SuffixLexicographicLess : public std::binary_function<const Range, const Range, bool> { bool operator()(const Range first, const Range second) const { for (const WordIndex *f = first.end() - 1, *s = second.end() - 1; f >= first.begin() && s >= second.begin(); --f, --s) { if (*f < *s) return true; if (*f > *s) return false; } return first.size() < second.size(); } }; } // namespace lm #endif // LM_COMMON_COMPARE_H
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/Makefile.am
if HAVE_COMPRESS compress_include_headers = fst/extensions/compress/compress.h \ fst/extensions/compress/compress-script.h fst/extensions/compress/gzfile.h \ fst/extensions/compress/elias.h fst/extensions/compress/randmod.h endif if HAVE_FAR far_include_headers = fst/extensions/far/compile-strings.h \ fst/extensions/far/create.h fst/extensions/far/equal.h \ fst/extensions/far/extract.h fst/extensions/far/far.h \ fst/extensions/far/far-class.h fst/extensions/far/farlib.h \ fst/extensions/far/farscript.h fst/extensions/far/getters.h \ fst/extensions/far/info.h fst/extensions/far/isomorphic.h \ fst/extensions/far/print-strings.h fst/extensions/far/script-impl.h \ fst/extensions/far/stlist.h fst/extensions/far/sttable.h endif if HAVE_LINEAR linear_include_headers = fst/extensions/linear/linear-fst-data-builder.h \ fst/extensions/linear/linear-fst-data.h fst/extensions/linear/linear-fst.h \ fst/extensions/linear/linearscript.h fst/extensions/linear/loglinear-apply.h \ fst/extensions/linear/trie.h endif if HAVE_MPDT mpdt_include_headers = fst/extensions/mpdt/compose.h \ fst/extensions/mpdt/expand.h fst/extensions/mpdt/info.h \ fst/extensions/mpdt/mpdt.h fst/extensions/mpdt/mpdtlib.h \ fst/extensions/mpdt/mpdtscript.h fst/extensions/mpdt/read_write_utils.h \ fst/extensions/mpdt/reverse.h endif if HAVE_NGRAM ngram_include_headers = fst/extensions/ngram/bitmap-index.h \ fst/extensions/ngram/ngram-fst.h fst/extensions/ngram/nthbit.h endif if HAVE_PDT pdt_include_headers = fst/extensions/pdt/collection.h \ fst/extensions/pdt/compose.h fst/extensions/pdt/expand.h \ fst/extensions/pdt/getters.h fst/extensions/pdt/info.h \ fst/extensions/pdt/paren.h fst/extensions/pdt/pdt.h \ fst/extensions/pdt/pdtlib.h fst/extensions/pdt/pdtscript.h \ fst/extensions/pdt/replace.h fst/extensions/pdt/reverse.h \ fst/extensions/pdt/shortest-path.h endif if HAVE_SPECIAL special_include_headers = fst/extensions/special/phi-fst.h \ fst/extensions/special/rho-fst.h fst/extensions/special/sigma-fst.h endif if HAVE_GRM far_include_headers = fst/extensions/far/compile-strings.h \ fst/extensions/far/create.h fst/extensions/far/equal.h \ fst/extensions/far/extract.h fst/extensions/far/far.h \ fst/extensions/far/far-class.h fst/extensions/far/farlib.h \ fst/extensions/far/farscript.h fst/extensions/far/getters.h \ fst/extensions/far/info.h fst/extensions/far/isomorphic.h \ fst/extensions/far/print-strings.h fst/extensions/far/script-impl.h \ fst/extensions/far/stlist.h fst/extensions/far/sttable.h mpdt_include_headers = fst/extensions/mpdt/compose.h \ fst/extensions/mpdt/expand.h fst/extensions/mpdt/info.h \ fst/extensions/mpdt/mpdt.h fst/extensions/mpdt/mpdtlib.h \ fst/extensions/mpdt/mpdtscript.h fst/extensions/mpdt/read_write_utils.h \ fst/extensions/mpdt/reverse.h pdt_include_headers = fst/extensions/pdt/collection.h \ fst/extensions/pdt/compose.h fst/extensions/pdt/expand.h \ fst/extensions/pdt/getters.h fst/extensions/pdt/info.h \ fst/extensions/pdt/paren.h fst/extensions/pdt/pdt.h \ fst/extensions/pdt/pdtlib.h fst/extensions/pdt/pdtscript.h \ fst/extensions/pdt/replace.h fst/extensions/pdt/reverse.h \ fst/extensions/pdt/shortest-path.h endif script_include_headers = fst/script/arc-class.h \ fst/script/arciterator-class.h fst/script/arcsort.h \ fst/script/arg-packs.h fst/script/closure.h fst/script/compile-impl.h \ fst/script/compile.h fst/script/compose.h fst/script/concat.h \ fst/script/connect.h fst/script/convert.h fst/script/decode.h \ fst/script/determinize.h fst/script/difference.h fst/script/disambiguate.h \ fst/script/draw-impl.h fst/script/draw.h fst/script/encode.h \ fst/script/encodemapper-class.h fst/script/epsnormalize.h fst/script/equal.h \ fst/script/equivalent.h fst/script/fst-class.h fst/script/fstscript.h \ fst/script/getters.h fst/script/info-impl.h fst/script/info.h \ fst/script/intersect.h fst/script/invert.h fst/script/isomorphic.h \ fst/script/map.h fst/script/minimize.h fst/script/print-impl.h \ fst/script/print.h fst/script/project.h fst/script/prune.h \ fst/script/push.h fst/script/randequivalent.h fst/script/randgen.h \ fst/script/register.h fst/script/relabel.h fst/script/replace.h \ fst/script/reverse.h fst/script/reweight.h fst/script/rmepsilon.h \ fst/script/script-impl.h fst/script/shortest-distance.h \ fst/script/shortest-path.h fst/script/stateiterator-class.h \ fst/script/synchronize.h fst/script/text-io.h fst/script/topsort.h \ fst/script/union.h fst/script/weight-class.h fst/script/fstscript-decl.h \ fst/script/verify.h nobase_include_HEADERS = fst/accumulator.h fst/add-on.h fst/arc-arena.h \ fst/arc-map.h fst/arc.h fst/arcfilter.h fst/arcsort.h fst/bi-table.h \ fst/cache.h fst/closure.h fst/compact-fst.h fst/compat.h fst/complement.h \ fst/compose-filter.h fst/compose.h fst/concat.h fst/config.h fst/connect.h \ fst/const-fst.h fst/determinize.h fst/dfs-visit.h fst/difference.h \ fst/disambiguate.h fst/edit-fst.h fst/encode.h fst/epsnormalize.h fst/equal.h \ fst/equivalent.h fst/expanded-fst.h fst/expectation-weight.h \ fst/factor-weight.h fst/filter-state.h fst/flags.h fst/float-weight.h \ fst/fst-decl.h fst/fst.h fst/fstlib.h fst/generic-register.h fst/heap.h \ fst/icu.h fst/intersect.h fst/interval-set.h fst/invert.h fst/isomorphic.h \ fst/label-reachable.h fst/lexicographic-weight.h fst/lock.h fst/log.h \ fst/lookahead-filter.h fst/lookahead-matcher.h fst/map.h fst/mapped-file.h \ fst/matcher-fst.h fst/matcher.h fst/memory.h fst/minimize.h fst/mutable-fst.h \ fst/pair-weight.h fst/partition.h fst/power-weight.h fst/product-weight.h \ fst/project.h fst/properties.h fst/prune.h fst/push.h fst/queue.h \ fst/randequivalent.h fst/randgen.h fst/rational.h fst/register.h \ fst/relabel.h fst/replace-util.h fst/replace.h fst/reverse.h fst/reweight.h \ fst/rmepsilon.h fst/rmfinalepsilon.h fst/set-weight.h fst/shortest-distance.h \ fst/shortest-path.h fst/signed-log-weight.h fst/sparse-power-weight.h \ fst/sparse-tuple-weight.h fst/state-map.h fst/state-reachable.h \ fst/state-table.h fst/statesort.h fst/string-weight.h fst/string.h \ fst/symbol-table-ops.h fst/symbol-table.h fst/synchronize.h \ fst/test-properties.h fst/topsort.h fst/tuple-weight.h fst/types.h \ fst/union-find.h fst/union-weight.h fst/union.h fst/util.h fst/vector-fst.h \ fst/verify.h fst/visit.h fst/weight.h \ $(compress_include_headers) \ $(far_include_headers) \ $(linear_include_headers) \ $(mpdt_include_headers) \ $(ngram_include_headers) \ $(pdt_include_headers) \ $(script_include_headers) \ $(special_include_headers)
0
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/framework/provider_shutdown.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once namespace onnxruntime { void UnloadSharedProviders(); }
0
coqui_public_repos/STT-models/amharic/itml
coqui_public_repos/STT-models/amharic/itml/v0.1.0/MODEL_CARD.md
# Model card for Amharic STT Jump to section: - [Model details](#model-details) - [Intended use](#intended-use) - [Performance Factors](#performance-factors) - [Metrics](#metrics) - [Training data](#training-data) - [Evaluation data](#evaluation-data) - [Ethical considerations](#ethical-considerations) - [Caveats and recommendations](#caveats-and-recommendations) ## Model details - Person or organization developing model: Originally trained by [Francis Tyers](https://scholar.google.fr/citations?user=o5HSM6cAAAAJ) and the [Inclusive Technology for Marginalised Languages](https://itml.cl.indiana.edu/) group. - Model language: Amharic / አማርኛ / `am` - Model date: April 26, 2021 - Model type: `Speech-to-Text` - Model version: `v0.1.0` - Compatible with 🐸 STT version: `v0.9.3` - License: AGPL - Citation details: `@techreport{amharic-stt, author = {Tyers,Francis}, title = {Amharic STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2021}, month = {April}, number = {STT-ALFFA-AM-0.1} }` - Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/). ## Intended use Speech-to-Text for the [Amharic Language](https://en.wikipedia.org/wiki/Amharic_language) on 16kHz, mono-channel audio. ## Performance Factors Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). ## Metrics STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk. #### Transcription Accuracy The following Word Error Rates and Character Error Rates are reported on [omnilingo](https://tepozcatl.omnilingo.cc/am/). |Test Corpus|WER|CER| |-----------|---|---| |ALFFA|75.1\%|29.4\%| #### Real-Time Factor Real-Time Factor (RTF) is defined as `processing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF. Recorded average RTF on laptop CPU: `` #### Model Size `model.pbmm`: 181M `model.tflite`: 46M ### Approaches to uncertainty and variability Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio. ## Training data This model was trained on the Amharic subset of the [ALFFA](http://openslr.org/25/) corpus. ## Evaluation data The Model was evaluated on the Amharic subset of the [ALFFA](http://openslr.org/25/) corpus. ## Ethical considerations Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use. ### Demographic Bias You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue. ### Surveillance Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech. ## Caveats and recommendations Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
0
coqui_public_repos/Trainer
coqui_public_repos/Trainer/tests/__init__.py
import os def run_cli(command): exit_status = os.system(command) assert exit_status == 0, f" [!] command `{command}` failed."
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/script/verify.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/verify.h> namespace fst { namespace script { bool Verify(const FstClass &fst) { VerifyArgs args(fst); Apply<Operation<VerifyArgs>>("Verify", fst.ArcType(), &args); return args.retval; } REGISTER_FST_OPERATION(Verify, StdArc, VerifyArgs); REGISTER_FST_OPERATION(Verify, LogArc, VerifyArgs); REGISTER_FST_OPERATION(Verify, Log64Arc, VerifyArgs); } // namespace script } // namespace fst
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/bin/fstrandgen-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Generates random paths through an FST. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/log.h> #include <fst/script/getters.h> #include <fst/script/randgen.h> DECLARE_int32(max_length); DECLARE_int32(npath); DECLARE_int32(seed); DECLARE_string(select); DECLARE_bool(weighted); DECLARE_bool(remove_total_weight); int fstrandgen_main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::VectorFstClass; string usage = "Generates random paths through an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } VLOG(1) << argv[0] << ": Seed = " << FLAGS_seed; const string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<FstClass> ifst(FstClass::Read(in_name)); if (!ifst) return 1; VectorFstClass ofst(ifst->ArcType()); s::RandArcSelection ras; if (!s::GetRandArcSelection(FLAGS_select, &ras)) { LOG(ERROR) << argv[0] << ": Unknown or unsupported select type " << FLAGS_select; return 1; } s::RandGen(*ifst, &ofst, FLAGS_seed, fst::RandGenOptions<s::RandArcSelection>( ras, FLAGS_max_length, FLAGS_npath, FLAGS_weighted, FLAGS_remove_total_weight)); return !ofst.Write(out_name); }
0
coqui_public_repos/inference-engine/third_party/kenlm/lm
coqui_public_repos/inference-engine/third_party/kenlm/lm/interpolate/normalize_test.cc
#include "lm/interpolate/normalize.hh" #include "lm/interpolate/interpolate_info.hh" #include "lm/interpolate/merge_probabilities.hh" #include "lm/common/ngram_stream.hh" #include "util/stream/chain.hh" #include "util/stream/multi_stream.hh" #define BOOST_TEST_MODULE NormalizeTest #include <boost/test/unit_test.hpp> namespace lm { namespace interpolate { namespace { // log without backoff const float kInputs[] = {-0.3, 1.2, -9.8, 4.0, -7.0, 0.0}; class WriteInput { public: WriteInput() {} void Run(const util::stream::ChainPosition &to) { util::stream::Stream out(to); for (WordIndex i = 0; i < sizeof(kInputs) / sizeof(float); ++i, ++out) { memcpy(out.Get(), &i, sizeof(WordIndex)); memcpy((uint8_t*)out.Get() + sizeof(WordIndex), &kInputs[i], sizeof(float)); } out.Poison(); } }; void CheckOutput(const util::stream::ChainPosition &from) { NGramStream<float> in(from); float sum = 0.0; for (WordIndex i = 0; i < sizeof(kInputs) / sizeof(float) - 1 /* <s> at the end */; ++i) { sum += pow(10.0, kInputs[i]); } sum = log10(sum); BOOST_REQUIRE(in); BOOST_CHECK_CLOSE(kInputs[0] - sum, in->Value(), 0.0001); BOOST_REQUIRE(++in); BOOST_CHECK_CLOSE(kInputs[1] - sum, in->Value(), 0.0001); BOOST_REQUIRE(++in); BOOST_CHECK_CLOSE(kInputs[2] - sum, in->Value(), 0.0001); BOOST_REQUIRE(++in); BOOST_CHECK_CLOSE(kInputs[3] - sum, in->Value(), 0.0001); BOOST_REQUIRE(++in); BOOST_CHECK_CLOSE(kInputs[4] - sum, in->Value(), 0.0001); BOOST_REQUIRE(++in); BOOST_CHECK_CLOSE(kInputs[5] - sum, in->Value(), 0.0001); BOOST_CHECK(!++in); } BOOST_AUTO_TEST_CASE(Unigrams) { InterpolateInfo info; info.lambdas.push_back(2.0); info.lambdas.push_back(-0.1); info.orders.push_back(1); info.orders.push_back(1); BOOST_CHECK_EQUAL(0, MakeEncoder(info, 1).EncodedLength()); // No backoffs. util::stream::Chains blank(0); util::FixedArray<util::stream::ChainPositions> models_by_order(2); models_by_order.push_back(blank); models_by_order.push_back(blank); util::stream::Chains merged_probabilities(1); util::stream::Chains probabilities_out(1); util::stream::Chains backoffs_out(0); merged_probabilities.push_back(util::stream::ChainConfig(sizeof(WordIndex) + sizeof(float) + sizeof(float), 2, 24)); probabilities_out.push_back(util::stream::ChainConfig(sizeof(WordIndex) + sizeof(float), 2, 100)); merged_probabilities[0] >> WriteInput(); Normalize(info, models_by_order, merged_probabilities, probabilities_out, backoffs_out); util::stream::ChainPosition checker(probabilities_out[0].Add()); merged_probabilities >> util::stream::kRecycle; probabilities_out >> util::stream::kRecycle; CheckOutput(checker); probabilities_out.Wait(); } }}} // namespaces
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/bin/fstdifference.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/flags.h> DEFINE_string(compose_filter, "auto", "Composition filter, one of: \"alt_sequence\", \"auto\", " "\"match\", \"null\", \"sequence\", \"trivial\""); DEFINE_bool(connect, true, "Trim output"); int fstdifference_main(int argc, char **argv); int main(int argc, char **argv) { return fstdifference_main(argc, argv); }
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/script/shortest-path.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/shortest-path.h> namespace fst { namespace script { void ShortestPath(const FstClass &ifst, MutableFstClass *ofst, const ShortestPathOptions &opts) { if (!internal::ArcTypesMatch(ifst, *ofst, "ShortestPath")) { ofst->SetProperties(kError, kError); return; } ShortestPathArgs args(ifst, ofst, opts); Apply<Operation<ShortestPathArgs>>("ShortestPath", ifst.ArcType(), &args); } REGISTER_FST_OPERATION(ShortestPath, StdArc, ShortestPathArgs); REGISTER_FST_OPERATION(ShortestPath, LogArc, ShortestPathArgs); REGISTER_FST_OPERATION(ShortestPath, Log64Arc, ShortestPathArgs); } // namespace script } // namespace fst
0
coqui_public_repos/STT-models/russian/jemeyer
coqui_public_repos/STT-models/russian/jemeyer/v0.1.0/alphabet.txt
а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ё
0
coqui_public_repos/TTS/docs/source
coqui_public_repos/TTS/docs/source/models/xtts.md
# ⓍTTS ⓍTTS is a super cool Text-to-Speech model that lets you clone voices in different languages by using just a quick 3-second audio clip. Built on the 🐢Tortoise, ⓍTTS has important model changes that make cross-language voice cloning and multi-lingual speech generation super easy. There is no need for an excessive amount of training data that spans countless hours. This is the same model that powers [Coqui Studio](https://coqui.ai/), and [Coqui API](https://docs.coqui.ai/docs), however we apply a few tricks to make it faster and support streaming inference. ### Features - Voice cloning. - Cross-language voice cloning. - Multi-lingual speech generation. - 24khz sampling rate. - Streaming inference with < 200ms latency. (See [Streaming inference](#streaming-inference)) - Fine-tuning support. (See [Training](#training)) ### Updates with v2 - Improved voice cloning. - Voices can be cloned with a single audio file or multiple audio files, without any effect on the runtime. - 2 new languages: Hungarian and Korean. - Across the board quality improvements. ### Code Current implementation only supports inference and GPT encoder training. ### Languages As of now, XTTS-v2 supports 16 languages: English (en), Spanish (es), French (fr), German (de), Italian (it), Portuguese (pt), Polish (pl), Turkish (tr), Russian (ru), Dutch (nl), Czech (cs), Arabic (ar), Chinese (zh-cn), Japanese (ja), Hungarian (hu) and Korean (ko). Stay tuned as we continue to add support for more languages. If you have any language requests, please feel free to reach out. ### License This model is licensed under [Coqui Public Model License](https://coqui.ai/cpml). ### Contact Come and join in our 🐸Community. We're active on [Discord](https://discord.gg/fBC58unbKE) and [Twitter](https://twitter.com/coqui_ai). You can also mail us at info@coqui.ai. ### Inference #### 🐸TTS Command line You can check all supported languages with the following command: ```console tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 \ --list_language_idx ``` You can check all Coqui available speakers with the following command: ```console tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 \ --list_speaker_idx ``` ##### Coqui speakers You can do inference using one of the available speakers using the following command: ```console tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 \ --text "It took me quite a long time to develop a voice, and now that I have it I'm not going to be silent." \ --speaker_idx "Ana Florence" \ --language_idx en \ --use_cuda true ``` ##### Clone a voice You can clone a speaker voice using a single or multiple references: ###### Single reference ```console tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 \ --text "Bugün okula gitmek istemiyorum." \ --speaker_wav /path/to/target/speaker.wav \ --language_idx tr \ --use_cuda true ``` ###### Multiple references ```console tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 \ --text "Bugün okula gitmek istemiyorum." \ --speaker_wav /path/to/target/speaker.wav /path/to/target/speaker_2.wav /path/to/target/speaker_3.wav \ --language_idx tr \ --use_cuda true ``` or for all wav files in a directory you can use: ```console tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 \ --text "Bugün okula gitmek istemiyorum." \ --speaker_wav /path/to/target/*.wav \ --language_idx tr \ --use_cuda true ``` #### 🐸TTS API ##### Clone a voice You can clone a speaker voice using a single or multiple references: ###### Single reference Splits the text into sentences and generates audio for each sentence. The audio files are then concatenated to produce the final audio. You can optionally disable sentence splitting for better coherence but more VRAM and possibly hitting models context length limit. ```python from TTS.api import TTS tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=True) # generate speech by cloning a voice using default settings tts.tts_to_file(text="It took me quite a long time to develop a voice, and now that I have it I'm not going to be silent.", file_path="output.wav", speaker_wav=["/path/to/target/speaker.wav"], language="en", split_sentences=True ) ``` ###### Multiple references You can pass multiple audio files to the `speaker_wav` argument for better voice cloning. ```python from TTS.api import TTS # using the default version set in 🐸TTS tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=True) # using a specific version # 👀 see the branch names for versions on https://huggingface.co/coqui/XTTS-v2/tree/main # ❗some versions might be incompatible with the API tts = TTS("xtts_v2.0.2", gpu=True) # getting the latest XTTS_v2 tts = TTS("xtts", gpu=True) # generate speech by cloning a voice using default settings tts.tts_to_file(text="It took me quite a long time to develop a voice, and now that I have it I'm not going to be silent.", file_path="output.wav", speaker_wav=["/path/to/target/speaker.wav", "/path/to/target/speaker_2.wav", "/path/to/target/speaker_3.wav"], language="en") ``` ##### Coqui speakers You can do inference using one of the available speakers using the following code: ```python from TTS.api import TTS tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=True) # generate speech by cloning a voice using default settings tts.tts_to_file(text="It took me quite a long time to develop a voice, and now that I have it I'm not going to be silent.", file_path="output.wav", speaker="Ana Florence", language="en", split_sentences=True ) ``` #### 🐸TTS Model API To use the model API, you need to download the model files and pass config and model file paths manually. #### Manual Inference If you want to be able to `load_checkpoint` with `use_deepspeed=True` and **enjoy the speedup**, you need to install deepspeed first. ```console pip install deepspeed==0.10.3 ``` ##### inference parameters - `text`: The text to be synthesized. - `language`: The language of the text to be synthesized. - `gpt_cond_latent`: The latent vector you get with get_conditioning_latents. (You can cache for faster inference with same speaker) - `speaker_embedding`: The speaker embedding you get with get_conditioning_latents. (You can cache for faster inference with same speaker) - `temperature`: The softmax temperature of the autoregressive model. Defaults to 0.65. - `length_penalty`: A length penalty applied to the autoregressive decoder. Higher settings causes the model to produce more terse outputs. Defaults to 1.0. - `repetition_penalty`: A penalty that prevents the autoregressive decoder from repeating itself during decoding. Can be used to reduce the incidence of long silences or "uhhhhhhs", etc. Defaults to 2.0. - `top_k`: Lower values mean the decoder produces more "likely" (aka boring) outputs. Defaults to 50. - `top_p`: Lower values mean the decoder produces more "likely" (aka boring) outputs. Defaults to 0.8. - `speed`: The speed rate of the generated audio. Defaults to 1.0. (can produce artifacts if far from 1.0) - `enable_text_splitting`: Whether to split the text into sentences and generate audio for each sentence. It allows you to have infinite input length but might loose important context between sentences. Defaults to True. ##### Inference ```python import os import torch import torchaudio from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts print("Loading model...") config = XttsConfig() config.load_json("/path/to/xtts/config.json") model = Xtts.init_from_config(config) model.load_checkpoint(config, checkpoint_dir="/path/to/xtts/", use_deepspeed=True) model.cuda() print("Computing speaker latents...") gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=["reference.wav"]) print("Inference...") out = model.inference( "It took me quite a long time to develop a voice and now that I have it I am not going to be silent.", "en", gpt_cond_latent, speaker_embedding, temperature=0.7, # Add custom parameters here ) torchaudio.save("xtts.wav", torch.tensor(out["wav"]).unsqueeze(0), 24000) ``` ##### Streaming manually Here the goal is to stream the audio as it is being generated. This is useful for real-time applications. Streaming inference is typically slower than regular inference, but it allows to get a first chunk of audio faster. ```python import os import time import torch import torchaudio from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts print("Loading model...") config = XttsConfig() config.load_json("/path/to/xtts/config.json") model = Xtts.init_from_config(config) model.load_checkpoint(config, checkpoint_dir="/path/to/xtts/", use_deepspeed=True) model.cuda() print("Computing speaker latents...") gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=["reference.wav"]) print("Inference...") t0 = time.time() chunks = model.inference_stream( "It took me quite a long time to develop a voice and now that I have it I am not going to be silent.", "en", gpt_cond_latent, speaker_embedding ) wav_chuncks = [] for i, chunk in enumerate(chunks): if i == 0: print(f"Time to first chunck: {time.time() - t0}") print(f"Received chunk {i} of audio length {chunk.shape[-1]}") wav_chuncks.append(chunk) wav = torch.cat(wav_chuncks, dim=0) torchaudio.save("xtts_streaming.wav", wav.squeeze().unsqueeze(0).cpu(), 24000) ``` ### Training #### Easy training To make `XTTS_v2` GPT encoder training easier for beginner users we did a gradio demo that implements the whole fine-tuning pipeline. The gradio demo enables the user to easily do the following steps: - Preprocessing of the uploaded audio or audio files in 🐸 TTS coqui formatter - Train the XTTS GPT encoder with the processed data - Inference support using the fine-tuned model The user can run this gradio demo locally or remotely using a Colab Notebook. ##### Run demo on Colab To make the `XTTS_v2` fine-tuning more accessible for users that do not have good GPUs available we did a Google Colab Notebook. The Colab Notebook is available [here](https://colab.research.google.com/drive/1GiI4_X724M8q2W-zZ-jXo7cWTV7RfaH-?usp=sharing). To learn how to use this Colab Notebook please check the [XTTS fine-tuning video](). If you are not able to acess the video you need to follow the steps: 1. Open the Colab notebook and start the demo by runining the first two cells (ignore pip install errors in the first one). 2. Click on the link "Running on public URL:" on the second cell output. 3. On the first Tab (1 - Data processing) you need to select the audio file or files, wait for upload, and then click on the button "Step 1 - Create dataset" and then wait until the dataset processing is done. 4. Soon as the dataset processing is done you need to go to the second Tab (2 - Fine-tuning XTTS Encoder) and press the button "Step 2 - Run the training" and then wait until the training is finished. Note that it can take up to 40 minutes. 5. Soon the training is done you can go to the third Tab (3 - Inference) and then click on the button "Step 3 - Load Fine-tuned XTTS model" and wait until the fine-tuned model is loaded. Then you can do the inference on the model by clicking on the button "Step 4 - Inference". ##### Run demo locally To run the demo locally you need to do the following steps: 1. Install 🐸 TTS following the instructions available [here](https://tts.readthedocs.io/en/dev/installation.html#installation). 2. Install the Gradio demo requirements with the command `python3 -m pip install -r TTS/demos/xtts_ft_demo/requirements.txt` 3. Run the Gradio demo using the command `python3 TTS/demos/xtts_ft_demo/xtts_demo.py` 4. Follow the steps presented in the [tutorial video](https://www.youtube.com/watch?v=8tpDiiouGxc&feature=youtu.be) to be able to fine-tune and test the fine-tuned model. If you are not able to access the video, here is what you need to do: 1. On the first Tab (1 - Data processing) select the audio file or files, wait for upload 2. Click on the button "Step 1 - Create dataset" and then wait until the dataset processing is done. 3. Go to the second Tab (2 - Fine-tuning XTTS Encoder) and press the button "Step 2 - Run the training" and then wait until the training is finished. it will take some time. 4. Go to the third Tab (3 - Inference) and then click on the button "Step 3 - Load Fine-tuned XTTS model" and wait until the fine-tuned model is loaded. 5. Now you can run inference with the model by clicking on the button "Step 4 - Inference". #### Advanced training A recipe for `XTTS_v2` GPT encoder training using `LJSpeech` dataset is available at https://github.com/coqui-ai/TTS/tree/dev/recipes/ljspeech/xtts_v1/train_gpt_xtts.py You need to change the fields of the `BaseDatasetConfig` to match your dataset and then update `GPTArgs` and `GPTTrainerConfig` fields as you need. By default, it will use the same parameters that XTTS v1.1 model was trained with. To speed up the model convergence, as default, it will also download the XTTS v1.1 checkpoint and load it. After training you can do inference following the code bellow. ```python import os import torch import torchaudio from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts # Add here the xtts_config path CONFIG_PATH = "recipes/ljspeech/xtts_v1/run/training/GPT_XTTS_LJSpeech_FT-October-23-2023_10+36AM-653f2e75/config.json" # Add here the vocab file that you have used to train the model TOKENIZER_PATH = "recipes/ljspeech/xtts_v1/run/training/XTTS_v2_original_model_files/vocab.json" # Add here the checkpoint that you want to do inference with XTTS_CHECKPOINT = "recipes/ljspeech/xtts_v1/run/training/GPT_XTTS_LJSpeech_FT/best_model.pth" # Add here the speaker reference SPEAKER_REFERENCE = "LjSpeech_reference.wav" # output wav path OUTPUT_WAV_PATH = "xtts-ft.wav" print("Loading model...") config = XttsConfig() config.load_json(CONFIG_PATH) model = Xtts.init_from_config(config) model.load_checkpoint(config, checkpoint_path=XTTS_CHECKPOINT, vocab_path=TOKENIZER_PATH, use_deepspeed=False) model.cuda() print("Computing speaker latents...") gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(audio_path=[SPEAKER_REFERENCE]) print("Inference...") out = model.inference( "It took me quite a long time to develop a voice and now that I have it I am not going to be silent.", "en", gpt_cond_latent, speaker_embedding, temperature=0.7, # Add custom parameters here ) torchaudio.save(OUTPUT_WAV_PATH, torch.tensor(out["wav"]).unsqueeze(0), 24000) ``` ## References and Acknowledgements - VallE: https://arxiv.org/abs/2301.02111 - Tortoise Repo: https://github.com/neonbjb/tortoise-tts - Faster implementation: https://github.com/152334H/tortoise-tts-fast - Univnet: https://arxiv.org/abs/2106.07889 - Latent Diffusion:https://arxiv.org/abs/2112.10752 - DALL-E: https://arxiv.org/abs/2102.12092 - Perceiver: https://arxiv.org/abs/2103.03206 ## XttsConfig ```{eval-rst} .. autoclass:: TTS.tts.configs.xtts_config.XttsConfig :members: ``` ## XttsArgs ```{eval-rst} .. autoclass:: TTS.tts.models.xtts.XttsArgs :members: ``` ## XTTS Model ```{eval-rst} .. autoclass:: TTS.tts.models.xtts.XTTS :members: ```
0
coqui_public_repos/STT/native_client
coqui_public_repos/STT/native_client/kenlm/README.coqui
KenLM source downloaded from https://github.com/kpu/kenlm on 2020/01/15 commit fee7b058bf3f96d570c852340729c0d4d4df2c25 This corresponds to https://github.com/kpu/kenlm/commit/fee7b058bf3f96d570c852340729c0d4d4df2c25 The following procedure was run to remove unneeded files: cd kenlm rm -rf windows include lm/filter lm/builder util/stream util/getopt.* python This was done in order to ensure uniqueness of kenlm_double_conversion: git grep 'kenlm_double_conversion' | cut -d':' -f1 | sort | uniq | xargs sed -ri 's/kenlm_double_conversion/kenlm_kenlm_double_conversion/g' Cherry-pick fix for MSVC: curl -vsSL https://github.com/kpu/kenlm/commit/d70e28403f07e88b276c6bd9f162d2a428530f2e.patch | git am -p1 --directory=native_client/kenlm Most of the KenLM code is licensed under the LGPL. There are exceptions that have their own licenses, listed below. See comments in those files for more details. util/getopt.* is getopt for Windows util/murmur_hash.cc util/string_piece.hh and util/string_piece.cc util/double-conversion/LICENSE covers util/double-conversion except the build files util/file.cc contains a modified implementation of mkstemp under the LGPL util/integer_to_string.* is BSD For the rest: KenLM is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. KenLM 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License 2.1 along with KenLM code. If not, see <http://www.gnu.org/licenses/lgpl-2.1.html>. util/double-conversion: Copyright 2006-2011, the V8 project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. util/integer_to_string.*: Copyright (C) 2014 Milo Yip 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.
0
coqui_public_repos/STT-examples/net_framework/STTWPF
coqui_public_repos/STT-examples/net_framework/STTWPF/ViewModels/BindableBase.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace STT.WPF.ViewModels { /// <summary> /// Implementation of <see cref="INotifyPropertyChanged"/> to simplify models. /// </summary> public abstract class BindableBase : INotifyPropertyChanged { /// <summary> /// Checks if a property already matches a desired value. Sets the property and /// notifies listeners only when necessary. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="storage">Reference to a property with both getter and setter.</param> /// <param name="value">Desired value for the property.</param> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers that /// support CallerMemberName.</param> /// <returns>True if the value was changed, false if the existing value matched the /// desired value.</returns> protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return true; } #region INotifyPropertyChanged /// <summary> /// Notifies listeners that a property value has changed. /// </summary> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers /// that support <see cref="CallerMemberNameAttribute"/>.</param> public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); #endregion } }
0
coqui_public_repos/TTS/TTS/vc/modules/freevc
coqui_public_repos/TTS/TTS/vc/modules/freevc/speaker_encoder/hparams.py
## Mel-filterbank mel_window_length = 25 # In milliseconds mel_window_step = 10 # In milliseconds mel_n_channels = 40 ## Audio sampling_rate = 16000 # Number of spectrogram frames in a partial utterance partials_n_frames = 160 # 1600 ms ## Voice Activation Detection # Window size of the VAD. Must be either 10, 20 or 30 milliseconds. # This sets the granularity of the VAD. Should not need to be changed. vad_window_length = 30 # In milliseconds # Number of frames to average together when performing the moving average smoothing. # The larger this value, the larger the VAD variations must be to not get smoothed out. vad_moving_average_width = 8 # Maximum number of consecutive silent frames a segment can have. vad_max_silence_length = 6 ## Audio volume normalization audio_norm_target_dBFS = -30 ## Model parameters model_hidden_size = 256 model_embedding_size = 256 model_num_layers = 3
0
coqui_public_repos/TTS/TTS/tts/utils/text
coqui_public_repos/TTS/TTS/tts/utils/text/english/number_norm.py
""" from https://github.com/keithito/tacotron """ import re from typing import Dict import inflect _inflect = inflect.engine() _comma_number_re = re.compile(r"([0-9][0-9\,]+[0-9])") _decimal_number_re = re.compile(r"([0-9]+\.[0-9]+)") _currency_re = re.compile(r"(£|\$|¥)([0-9\,\.]*[0-9]+)") _ordinal_re = re.compile(r"[0-9]+(st|nd|rd|th)") _number_re = re.compile(r"-?[0-9]+") def _remove_commas(m): return m.group(1).replace(",", "") def _expand_decimal_point(m): return m.group(1).replace(".", " point ") def __expand_currency(value: str, inflection: Dict[float, str]) -> str: parts = value.replace(",", "").split(".") if len(parts) > 2: return f"{value} {inflection[2]}" # Unexpected format text = [] integer = int(parts[0]) if parts[0] else 0 if integer > 0: integer_unit = inflection.get(integer, inflection[2]) text.append(f"{integer} {integer_unit}") fraction = int(parts[1]) if len(parts) > 1 and parts[1] else 0 if fraction > 0: fraction_unit = inflection.get(fraction / 100, inflection[0.02]) text.append(f"{fraction} {fraction_unit}") if len(text) == 0: return f"zero {inflection[2]}" return " ".join(text) def _expand_currency(m: "re.Match") -> str: currencies = { "$": { 0.01: "cent", 0.02: "cents", 1: "dollar", 2: "dollars", }, "€": { 0.01: "cent", 0.02: "cents", 1: "euro", 2: "euros", }, "£": { 0.01: "penny", 0.02: "pence", 1: "pound sterling", 2: "pounds sterling", }, "¥": { # TODO rin 0.02: "sen", 2: "yen", }, } unit = m.group(1) currency = currencies[unit] value = m.group(2) return __expand_currency(value, currency) def _expand_ordinal(m): return _inflect.number_to_words(m.group(0)) def _expand_number(m): num = int(m.group(0)) if 1000 < num < 3000: if num == 2000: return "two thousand" if 2000 < num < 2010: return "two thousand " + _inflect.number_to_words(num % 100) if num % 100 == 0: return _inflect.number_to_words(num // 100) + " hundred" return _inflect.number_to_words(num, andword="", zero="oh", group=2).replace(", ", " ") return _inflect.number_to_words(num, andword="") def normalize_numbers(text): text = re.sub(_comma_number_re, _remove_commas, text) text = re.sub(_currency_re, _expand_currency, text) text = re.sub(_decimal_number_re, _expand_decimal_point, text) text = re.sub(_ordinal_re, _expand_ordinal, text) text = re.sub(_number_re, _expand_number, text) return text
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/bin/fstepsnormalize-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Epsilon-normalizes an FST. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/script/epsnormalize.h> #include <fst/script/getters.h> DECLARE_bool(eps_norm_output); int fstepsnormalize_main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::VectorFstClass; string usage = "Epsilon normalizes an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<FstClass> ifst(FstClass::Read(in_name)); if (!ifst) return 1; VectorFstClass ofst(ifst->ArcType()); s::EpsNormalize(*ifst, &ofst, s::GetEpsNormalizeType(FLAGS_eps_norm_output)); return !ofst.Write(out_name); }
0
coqui_public_repos/inference-engine/third_party/kenlm
coqui_public_repos/inference-engine/third_party/kenlm/util/pool.hh
#ifndef UTIL_POOL_H #define UTIL_POOL_H #include <cassert> #include <cstring> #include <vector> #include <stdint.h> namespace util { /* Very simple pool. It can only allocate memory. And all of the memory it * allocates must be freed at the same time. */ class Pool { public: Pool(); ~Pool(); void *Allocate(std::size_t size) { void *ret = current_; current_ += size; if (current_ > current_end_) { ret = More(size); } #ifdef DEBUG base_check_ = ret; #endif return ret; } /** Extend (or contract) the most recent allocation. * @param base The base pointer of the allocation. This must must have been * returned by the MOST RECENT call to Allocate or Continue. * @param additional Change in the size. * * In most cases, more memory from the same page is used, in which case * base is unchanged and the function returns false. * If the page runs out, a new page is created and the memory (from base) * is copied. The function returns true. * * @return Whether the base had to be changed due to allocating a page. */ bool Continue(void *&base, std::ptrdiff_t additional) { #ifdef DEBUG assert(base == base_check_); #endif current_ += additional; if (current_ > current_end_) { std::size_t new_total = current_ - static_cast<uint8_t*>(base); void *new_base = More(new_total); std::memcpy(new_base, base, new_total - additional); base = new_base; #ifdef DEBUG base_check_ = base; #endif return true; } return false; } void FreeAll(); private: void *More(std::size_t size); std::vector<void *> free_list_; uint8_t *current_, *current_end_; #ifdef DEBUG // For debugging, check that Continue came from the most recent call. void *base_check_; #endif // DEBUG // no copying Pool(const Pool &); Pool &operator=(const Pool &); }; /** * Pool designed to allow limited freeing. * Keeps a linked list of free elements in the free spaces. * Will not reduce in size until FreeAll is called. */ class FreePool { public: explicit FreePool(std::size_t element_size) : free_list_(NULL), element_size_(element_size) {} void *Allocate() { if (free_list_) { void *ret = free_list_; free_list_ = *reinterpret_cast<void**>(free_list_); return ret; } else { return backing_.Allocate(element_size_); } } void Free(void *ptr) { *reinterpret_cast<void**>(ptr) = free_list_; free_list_ = ptr; } std::size_t ElementSize() const { return element_size_; } private: void *free_list_; Pool backing_; const std::size_t element_size_; }; } // namespace util #endif // UTIL_POOL_H
0
coqui_public_repos/inference-engine/third_party/kenlm/lm
coqui_public_repos/inference-engine/third_party/kenlm/lm/interpolate/backoff_reunification.cc
#include "lm/interpolate/backoff_reunification.hh" #include "lm/common/model_buffer.hh" #include "lm/common/ngram_stream.hh" #include "lm/common/ngram.hh" #include "lm/common/compare.hh" #include <algorithm> #include <cassert> namespace lm { namespace interpolate { namespace { class MergeWorker { public: MergeWorker(std::size_t order, const util::stream::ChainPosition &prob_pos, const util::stream::ChainPosition &boff_pos) : order_(order), prob_pos_(prob_pos), boff_pos_(boff_pos) { // nothing } void Run(const util::stream::ChainPosition &position) { lm::NGramStream<ProbBackoff> stream(position); lm::NGramStream<float> prob_input(prob_pos_); util::stream::Stream boff_input(boff_pos_); for (; prob_input && boff_input; ++prob_input, ++boff_input, ++stream) { std::copy(prob_input->begin(), prob_input->end(), stream->begin()); stream->Value().prob = std::min(0.0f, prob_input->Value()); stream->Value().backoff = *reinterpret_cast<float *>(boff_input.Get()); } UTIL_THROW_IF2(prob_input || boff_input, "Streams were not the same size during merging"); stream.Poison(); } private: std::size_t order_; util::stream::ChainPosition prob_pos_; util::stream::ChainPosition boff_pos_; }; } // Since we are *adding* something to the output chain here, we pass in the // chain itself so that we can safely add a new step to the chain without // creating a deadlock situation (since creating a new ChainPosition will // make a new input/output pair---we want that position to be created // *here*, not before). void ReunifyBackoff(util::stream::ChainPositions &prob_pos, util::stream::ChainPositions &boff_pos, util::stream::Chains &output_chains) { assert(prob_pos.size() == boff_pos.size()); for (size_t i = 0; i < prob_pos.size(); ++i) output_chains[i] >> MergeWorker(i + 1, prob_pos[i], boff_pos[i]); } } }
0
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/common
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/common/logging/isink.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <string> #include "core/common/logging/logging.h" namespace onnxruntime { namespace logging { class ISink { public: ISink() = default; /** Sends the message to the sink. @param timestamp The timestamp. @param logger_id The logger identifier. @param message The captured message. */ void Send(const Timestamp& timestamp, const std::string& logger_id, const Capture& message) { SendImpl(timestamp, logger_id, message); } /** Sends a Profiling Event Record to the sink. @param Profiling Event Record */ virtual void SendProfileEvent(profiling::EventRecord&) const {}; virtual ~ISink() = default; private: // Make Code Analysis happy by disabling all for now. Enable as needed. ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ISink); virtual void SendImpl(const Timestamp& timestamp, const std::string& logger_id, const Capture& message) = 0; }; } // namespace logging } // namespace onnxruntime
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/state-reachable.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Class to determine whether a given (final) state can be reached from some // other given state. #ifndef FST_STATE_REACHABLE_H_ #define FST_STATE_REACHABLE_H_ #include <vector> #include <fst/log.h> #include <fst/connect.h> #include <fst/dfs-visit.h> #include <fst/fst.h> #include <fst/interval-set.h> #include <fst/vector-fst.h> namespace fst { // Computes the (final) states reachable from a given state in an FST. After // this visitor has been called, a final state f can be reached from a state // s iff (*isets)[s].Member(state2index[f]) is true, where (*isets[s]) is a // set of half-open inteval of final state indices and state2index[f] maps from // a final state to its index. If state2index is empty, it is filled-in with // suitable indices. If it is non-empty, those indices are used; in this case, // the final states must have out-degree 0. template <class Arc, class I = typename Arc::StateId, class S = IntervalSet<I>> class IntervalReachVisitor { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using Index = I; using ISet = S; using Interval = typename ISet::Interval; IntervalReachVisitor(const Fst<Arc> &fst, std::vector<S> *isets, std::vector<Index> *state2index) : fst_(fst), isets_(isets), state2index_(state2index), index_(state2index->empty() ? 1 : -1), error_(false) { isets_->clear(); } void InitVisit(const Fst<Arc> &) { error_ = false; } bool InitState(StateId s, StateId r) { while (isets_->size() <= s) isets_->push_back(S()); while (state2index_->size() <= s) state2index_->push_back(-1); if (fst_.Final(s) != Weight::Zero()) { // Create tree interval. auto *intervals = (*isets_)[s].MutableIntervals(); if (index_ < 0) { // Uses state2index_ map to set index. if (fst_.NumArcs(s) > 0) { FSTERROR() << "IntervalReachVisitor: state2index map must be empty " << "for this FST"; error_ = true; return false; } const auto index = (*state2index_)[s]; if (index < 0) { FSTERROR() << "IntervalReachVisitor: state2index map incomplete"; error_ = true; return false; } intervals->push_back(Interval(index, index + 1)); } else { // Use pre-order index. intervals->push_back(Interval(index_, index_ + 1)); (*state2index_)[s] = index_++; } } return true; } constexpr bool TreeArc(StateId, const Arc &) const { return true; } bool BackArc(StateId s, const Arc &arc) { FSTERROR() << "IntervalReachVisitor: Cyclic input"; error_ = true; return false; } bool ForwardOrCrossArc(StateId s, const Arc &arc) { // Non-tree interval. (*isets_)[s].Union((*isets_)[arc.nextstate]); return true; } void FinishState(StateId s, StateId p, const Arc *) { if (index_ >= 0 && fst_.Final(s) != Weight::Zero()) { auto *intervals = (*isets_)[s].MutableIntervals(); (*intervals)[0].end = index_; // Updates tree interval end. } (*isets_)[s].Normalize(); if (p != kNoStateId) { (*isets_)[p].Union((*isets_)[s]); // Propagates intervals to parent. } } void FinishVisit() {} bool Error() const { return error_; } private: const Fst<Arc> &fst_; std::vector<ISet> *isets_; std::vector<Index> *state2index_; Index index_; bool error_; }; // Tests reachability of final states from a given state. To test for // reachability from a state s, first do SetState(s). Then a final state f can // be reached from state s of FST iff Reach(f) is true. The input can be cyclic, // but no cycle may contain a final state. template <class Arc, class I = typename Arc::StateId, class S = IntervalSet<I>> class StateReachable { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using Index = I; using ISet = S; using Interval = typename ISet::Interval; explicit StateReachable(const Fst<Arc> &fst) : error_(false) { if (fst.Properties(kAcyclic, true)) { AcyclicStateReachable(fst); } else { CyclicStateReachable(fst); } } explicit StateReachable(const StateReachable<Arc> &reachable) { FSTERROR() << "Copy constructor for state reachable class " << "not implemented."; error_ = true; } // Sets current state. void SetState(StateId s) { s_ = s; } // Can reach this final state from current state? bool Reach(StateId s) { if (s >= state2index_.size()) return false; const auto i = state2index_[s]; if (i < 0) { FSTERROR() << "StateReachable: State non-final: " << s; error_ = true; return false; } return isets_[s_].Member(i); } // Access to the state-to-index mapping. Unassigned states have index -1. std::vector<Index> &State2Index() { return state2index_; } // Access to the interval sets. These specify the reachability to the final // states as intervals of the final state indices. const std::vector<ISet> &IntervalSets() { return isets_; } bool Error() const { return error_; } private: void AcyclicStateReachable(const Fst<Arc> &fst) { IntervalReachVisitor<Arc, StateId, ISet> reach_visitor(fst, &isets_, &state2index_); DfsVisit(fst, &reach_visitor); if (reach_visitor.Error()) error_ = true; } void CyclicStateReachable(const Fst<Arc> &fst) { // Finds state reachability on the acyclic condensation FST. VectorFst<Arc> cfst; std::vector<StateId> scc; Condense(fst, &cfst, &scc); StateReachable reachable(cfst); if (reachable.Error()) { error_ = true; return; } // Gets the number of states per SCC. std::vector<size_t> nscc; for (StateId s = 0; s < scc.size(); ++s) { const auto c = scc[s]; while (c >= nscc.size()) nscc.push_back(0); ++nscc[c]; } // Constructs the interval sets and state index mapping for the original // FST from the condensation FST. state2index_.resize(scc.size(), -1); isets_.resize(scc.size()); for (StateId s = 0; s < scc.size(); ++s) { const auto c = scc[s]; isets_[s] = reachable.IntervalSets()[c]; state2index_[s] = reachable.State2Index()[c]; // Checks that each final state in an input FST is not contained in a // cycle (i.e., not in a non-trivial SCC). if (cfst.Final(c) != Weight::Zero() && nscc[c] > 1) { FSTERROR() << "StateReachable: Final state contained in a cycle"; error_ = true; return; } } } StateId s_; // Current state. std::vector<ISet> isets_; // Interval sets per state. std::vector<Index> state2index_; // Finds index for a final state. bool error_; StateReachable &operator=(const StateReachable &) = delete; }; } // namespace fst #endif // FST_STATE_REACHABLE_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-electronjs_v5.0_16k-linux-amd64-opt.yml
build: template_file: test-linux-opt-base.tyml docker_image: "ubuntu:16.04" dependencies: - "linux-amd64-cpu-opt" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${nodejs.packages_xenial.prep_12} && ${nodejs.packages_xenial.apt_pinning} && apt-get -qq update && apt-get -qq -y install ${nodejs.packages_xenial.apt} ${electronjs.packages_xenial.apt} args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-electron-tests.sh 12.x 5.0.6 16k" workerType: "${docker.dsTests}" metadata: name: "DeepSpeech Linux AMD64 CPU ElectronJS v5.0 tests (16kHz)" description: "Testing DeepSpeech for Linux/AMD64 on ElectronJS v5.0, CPU only, optimized version (16kHz)"
0
coqui_public_repos/STT/native_client/kenlm
coqui_public_repos/STT/native_client/kenlm/lm/virtual_interface.cc
#include "virtual_interface.hh" #include "lm_exception.hh" namespace lm { namespace base { Vocabulary::~Vocabulary() {} void Vocabulary::SetSpecial(WordIndex begin_sentence, WordIndex end_sentence, WordIndex not_found) { begin_sentence_ = begin_sentence; end_sentence_ = end_sentence; not_found_ = not_found; } Model::~Model() {} } // namespace base } // namespace lm
0
coqui_public_repos/STT/native_client/kenlm
coqui_public_repos/STT/native_client/kenlm/lm/model_test.cc
#include "model.hh" #include <cstdlib> #include <cstring> #define BOOST_TEST_MODULE ModelTest #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> // Apparently some Boost versions use templates and are pretty strict about types matching. #define SLOPPY_CHECK_CLOSE(ref, value, tol) BOOST_CHECK_CLOSE(static_cast<double>(ref), static_cast<double>(value), static_cast<double>(tol)); namespace lm { namespace ngram { std::ostream &operator<<(std::ostream &o, const State &state) { o << "State length " << static_cast<unsigned int>(state.length) << ':'; for (const WordIndex *i = state.words; i < state.words + state.length; ++i) { o << ' ' << *i; } return o; } namespace { // Stupid bjam reverses the command line arguments randomly. const char *TestLocation() { if (boost::unit_test::framework::master_test_suite().argc < 3) { return "test.arpa"; } char **argv = boost::unit_test::framework::master_test_suite().argv; return argv[strstr(argv[1], "nounk") ? 2 : 1]; } const char *TestNoUnkLocation() { if (boost::unit_test::framework::master_test_suite().argc < 3) { return "test_nounk.arpa"; } char **argv = boost::unit_test::framework::master_test_suite().argv; return argv[strstr(argv[1], "nounk") ? 1 : 2]; } template <class Model> State GetState(const Model &model, const char *word, const State &in) { WordIndex context[in.length + 1]; context[0] = model.GetVocabulary().Index(word); std::copy(in.words, in.words + in.length, context + 1); State ret; model.GetState(context, context + in.length + 1, ret); return ret; } #define StartTest(word, ngram, score, indep_left) \ ret = model.FullScore( \ state, \ model.GetVocabulary().Index(word), \ out);\ SLOPPY_CHECK_CLOSE(score, ret.prob, 0.001); \ BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \ BOOST_CHECK_GE(std::min<unsigned char>(ngram, 5 - 1), out.length); \ BOOST_CHECK_EQUAL(indep_left, ret.independent_left); \ BOOST_CHECK_EQUAL(out, GetState(model, word, state)); #define AppendTest(word, ngram, score, indep_left) \ StartTest(word, ngram, score, indep_left) \ state = out; template <class M> void Starters(const M &model) { FullScoreReturn ret; Model::State state(model.BeginSentenceState()); Model::State out; StartTest("looking", 2, -0.4846522, true); // , probability plus <s> backoff StartTest(",", 1, -1.383514 + -0.4149733, true); // <unk> probability plus <s> backoff StartTest("this_is_not_found", 1, -1.995635 + -0.4149733, true); } template <class M> void Continuation(const M &model) { FullScoreReturn ret; Model::State state(model.BeginSentenceState()); Model::State out; AppendTest("looking", 2, -0.484652, true); AppendTest("on", 3, -0.348837, true); AppendTest("a", 4, -0.0155266, true); AppendTest("little", 5, -0.00306122, true); State preserve = state; AppendTest("the", 1, -4.04005, true); AppendTest("biarritz", 1, -1.9889, true); AppendTest("not_found", 1, -2.29666, true); AppendTest("more", 1, -1.20632 - 20.0, true); AppendTest(".", 2, -0.51363, true); AppendTest("</s>", 3, -0.0191651, true); BOOST_CHECK_EQUAL(0, state.length); state = preserve; AppendTest("more", 5, -0.00181395, true); BOOST_CHECK_EQUAL(4, state.length); AppendTest("loin", 5, -0.0432557, true); BOOST_CHECK_EQUAL(1, state.length); } template <class M> void Blanks(const M &model) { FullScoreReturn ret; State state(model.NullContextState()); State out; AppendTest("also", 1, -1.687872, false); AppendTest("would", 2, -2, true); AppendTest("consider", 3, -3, true); State preserve = state; AppendTest("higher", 4, -4, true); AppendTest("looking", 5, -5, true); BOOST_CHECK_EQUAL(1, state.length); state = preserve; // also would consider not_found AppendTest("not_found", 1, -1.995635 - 7.0 - 0.30103, true); state = model.NullContextState(); // higher looking is a blank. AppendTest("higher", 1, -1.509559, false); AppendTest("looking", 2, -1.285941 - 0.30103, false); State higher_looking = state; BOOST_CHECK_EQUAL(1, state.length); AppendTest("not_found", 1, -1.995635 - 0.4771212, true); state = higher_looking; // higher looking consider AppendTest("consider", 1, -1.687872 - 0.4771212, true); state = model.NullContextState(); AppendTest("would", 1, -1.687872, false); BOOST_CHECK_EQUAL(1, state.length); AppendTest("consider", 2, -1.687872 -0.30103, false); BOOST_CHECK_EQUAL(2, state.length); AppendTest("higher", 3, -1.509559 - 0.30103, false); BOOST_CHECK_EQUAL(3, state.length); AppendTest("looking", 4, -1.285941 - 0.30103, false); } template <class M> void Unknowns(const M &model) { FullScoreReturn ret; State state(model.NullContextState()); State out; AppendTest("not_found", 1, -1.995635, false); State preserve = state; AppendTest("not_found2", 2, -15.0, true); AppendTest("not_found3", 2, -15.0 - 2.0, true); state = preserve; AppendTest("however", 2, -4, true); AppendTest("not_found3", 3, -6, true); } template <class M> void MinimalState(const M &model) { FullScoreReturn ret; State state(model.NullContextState()); State out; AppendTest("baz", 1, -6.535897, true); BOOST_CHECK_EQUAL(0, state.length); state = model.NullContextState(); AppendTest("foo", 1, -3.141592, true); BOOST_CHECK_EQUAL(1, state.length); AppendTest("bar", 2, -6.0, true); // Has to include the backoff weight. BOOST_CHECK_EQUAL(1, state.length); AppendTest("bar", 1, -2.718281 + 3.0, true); BOOST_CHECK_EQUAL(1, state.length); state = model.NullContextState(); AppendTest("to", 1, -1.687872, false); AppendTest("look", 2, -0.2922095, true); BOOST_CHECK_EQUAL(2, state.length); AppendTest("a", 3, -7, true); } template <class M> void ExtendLeftTest(const M &model) { State right; FullScoreReturn little(model.FullScore(model.NullContextState(), model.GetVocabulary().Index("little"), right)); const float kLittleProb = -1.285941; SLOPPY_CHECK_CLOSE(kLittleProb, little.prob, 0.001); unsigned char next_use; float backoff_out[4]; FullScoreReturn extend_none(model.ExtendLeft(NULL, NULL, NULL, little.extend_left, 1, NULL, next_use)); BOOST_CHECK_EQUAL(0, next_use); BOOST_CHECK_EQUAL(little.extend_left, extend_none.extend_left); SLOPPY_CHECK_CLOSE(little.prob - little.rest, extend_none.prob, 0.001); BOOST_CHECK_EQUAL(1, extend_none.ngram_length); const WordIndex a = model.GetVocabulary().Index("a"); float backoff_in = 3.14; // a little FullScoreReturn extend_a(model.ExtendLeft(&a, &a + 1, &backoff_in, little.extend_left, 1, backoff_out, next_use)); BOOST_CHECK_EQUAL(1, next_use); SLOPPY_CHECK_CLOSE(-0.69897, backoff_out[0], 0.001); SLOPPY_CHECK_CLOSE(-0.09132547 - little.rest, extend_a.prob, 0.001); BOOST_CHECK_EQUAL(2, extend_a.ngram_length); BOOST_CHECK(!extend_a.independent_left); const WordIndex on = model.GetVocabulary().Index("on"); FullScoreReturn extend_on(model.ExtendLeft(&on, &on + 1, &backoff_in, extend_a.extend_left, 2, backoff_out, next_use)); BOOST_CHECK_EQUAL(1, next_use); SLOPPY_CHECK_CLOSE(-0.4771212, backoff_out[0], 0.001); SLOPPY_CHECK_CLOSE(-0.0283603 - (extend_a.rest + little.rest), extend_on.prob, 0.001); BOOST_CHECK_EQUAL(3, extend_on.ngram_length); BOOST_CHECK(!extend_on.independent_left); const WordIndex both[2] = {a, on}; float backoff_in_arr[4]; FullScoreReturn extend_both(model.ExtendLeft(both, both + 2, backoff_in_arr, little.extend_left, 1, backoff_out, next_use)); BOOST_CHECK_EQUAL(2, next_use); SLOPPY_CHECK_CLOSE(-0.69897, backoff_out[0], 0.001); SLOPPY_CHECK_CLOSE(-0.4771212, backoff_out[1], 0.001); SLOPPY_CHECK_CLOSE(-0.0283603 - little.rest, extend_both.prob, 0.001); BOOST_CHECK_EQUAL(3, extend_both.ngram_length); BOOST_CHECK(!extend_both.independent_left); BOOST_CHECK_EQUAL(extend_on.extend_left, extend_both.extend_left); } #define StatelessTest(word, provide, ngram, score) \ ret = model.FullScoreForgotState(indices + num_words - word, indices + num_words - word + provide, indices[num_words - word - 1], state); \ SLOPPY_CHECK_CLOSE(score, ret.prob, 0.001); \ BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \ model.GetState(indices + num_words - word, indices + num_words - word + provide, before); \ ret = model.FullScore(before, indices[num_words - word - 1], out); \ BOOST_CHECK(state == out); \ SLOPPY_CHECK_CLOSE(score, ret.prob, 0.001); \ BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); template <class M> void Stateless(const M &model) { const char *words[] = {"<s>", "looking", "on", "a", "little", "the", "biarritz", "not_found", "more", ".", "</s>"}; const size_t num_words = sizeof(words) / sizeof(const char*); // Silience "array subscript is above array bounds" when extracting end pointer. WordIndex indices[num_words + 1]; for (unsigned int i = 0; i < num_words; ++i) { indices[num_words - 1 - i] = model.GetVocabulary().Index(words[i]); } FullScoreReturn ret; State state, out, before; ret = model.FullScoreForgotState(indices + num_words - 1, indices + num_words, indices[num_words - 2], state); SLOPPY_CHECK_CLOSE(-0.484652, ret.prob, 0.001); StatelessTest(1, 1, 2, -0.484652); // looking StatelessTest(1, 2, 2, -0.484652); // on AppendTest("on", 3, -0.348837, true); StatelessTest(2, 3, 3, -0.348837); StatelessTest(2, 2, 3, -0.348837); StatelessTest(2, 1, 2, -0.4638903); // a StatelessTest(3, 4, 4, -0.0155266); // little AppendTest("little", 5, -0.00306122, true); StatelessTest(4, 5, 5, -0.00306122); // the AppendTest("the", 1, -4.04005, true); StatelessTest(5, 5, 1, -4.04005); // No context of the. StatelessTest(5, 0, 1, -1.687872); // biarritz StatelessTest(6, 1, 1, -1.9889); // not found StatelessTest(7, 1, 1, -2.29666); StatelessTest(7, 0, 1, -1.995635); WordIndex unk[1]; unk[0] = 0; model.GetState(unk, unk + 1, state); BOOST_CHECK_EQUAL(1, state.length); BOOST_CHECK_EQUAL(static_cast<WordIndex>(0), state.words[0]); } template <class M> void NoUnkCheck(const M &model) { WordIndex unk_index = 0; State state; FullScoreReturn ret = model.FullScoreForgotState(&unk_index, &unk_index + 1, unk_index, state); SLOPPY_CHECK_CLOSE(-100.0, ret.prob, 0.001); } template <class M> void Everything(const M &m) { Starters(m); Continuation(m); Blanks(m); Unknowns(m); MinimalState(m); ExtendLeftTest(m); Stateless(m); } class ExpectEnumerateVocab : public EnumerateVocab { public: ExpectEnumerateVocab() {} void Add(WordIndex index, const StringPiece &str) { BOOST_CHECK_EQUAL(seen.size(), index); seen.push_back(std::string(str.data(), str.length())); } void Check(const base::Vocabulary &vocab) { BOOST_CHECK_EQUAL(37ULL, seen.size()); BOOST_REQUIRE(!seen.empty()); BOOST_CHECK_EQUAL("<unk>", seen[0]); for (WordIndex i = 0; i < seen.size(); ++i) { BOOST_CHECK_EQUAL(i, vocab.Index(seen[i])); } } void Clear() { seen.clear(); } std::vector<std::string> seen; }; template <class ModelT> void LoadingTest() { Config config; config.arpa_complain = Config::NONE; config.messages = NULL; config.probing_multiplier = 2.0; { ExpectEnumerateVocab enumerate; config.enumerate_vocab = &enumerate; ModelT m(TestLocation(), config); enumerate.Check(m.GetVocabulary()); BOOST_CHECK_EQUAL((WordIndex)37, m.GetVocabulary().Bound()); Everything(m); } { ExpectEnumerateVocab enumerate; config.enumerate_vocab = &enumerate; ModelT m(TestNoUnkLocation(), config); enumerate.Check(m.GetVocabulary()); BOOST_CHECK_EQUAL((WordIndex)37, m.GetVocabulary().Bound()); NoUnkCheck(m); } } BOOST_AUTO_TEST_CASE(probing) { LoadingTest<Model>(); } BOOST_AUTO_TEST_CASE(trie) { LoadingTest<TrieModel>(); } BOOST_AUTO_TEST_CASE(quant_trie) { LoadingTest<QuantTrieModel>(); } BOOST_AUTO_TEST_CASE(bhiksha_trie) { LoadingTest<ArrayTrieModel>(); } BOOST_AUTO_TEST_CASE(quant_bhiksha_trie) { LoadingTest<QuantArrayTrieModel>(); } template <class ModelT> void BinaryTest(Config::WriteMethod write_method) { Config config; config.write_mmap = "test.binary"; config.messages = NULL; config.write_method = write_method; ExpectEnumerateVocab enumerate; config.enumerate_vocab = &enumerate; { ModelT copy_model(TestLocation(), config); enumerate.Check(copy_model.GetVocabulary()); enumerate.Clear(); Everything(copy_model); } config.write_mmap = NULL; ModelType type; BOOST_REQUIRE(RecognizeBinary("test.binary", type)); BOOST_CHECK_EQUAL(ModelT::kModelType, type); { ModelT binary("test.binary", config); enumerate.Check(binary.GetVocabulary()); Everything(binary); } unlink("test.binary"); // Now test without <unk>. config.write_mmap = "test_nounk.binary"; config.messages = NULL; enumerate.Clear(); { ModelT copy_model(TestNoUnkLocation(), config); enumerate.Check(copy_model.GetVocabulary()); enumerate.Clear(); NoUnkCheck(copy_model); } config.write_mmap = NULL; { ModelT binary(TestNoUnkLocation(), config); enumerate.Check(binary.GetVocabulary()); NoUnkCheck(binary); } unlink("test_nounk.binary"); } template <class ModelT> void BinaryTest() { BinaryTest<ModelT>(Config::WRITE_MMAP); BinaryTest<ModelT>(Config::WRITE_AFTER); } BOOST_AUTO_TEST_CASE(write_and_read_probing) { BinaryTest<ProbingModel>(); } BOOST_AUTO_TEST_CASE(write_and_read_rest_probing) { BinaryTest<RestProbingModel>(); } BOOST_AUTO_TEST_CASE(write_and_read_trie) { BinaryTest<TrieModel>(); } BOOST_AUTO_TEST_CASE(write_and_read_quant_trie) { BinaryTest<QuantTrieModel>(); } BOOST_AUTO_TEST_CASE(write_and_read_array_trie) { BinaryTest<ArrayTrieModel>(); } BOOST_AUTO_TEST_CASE(write_and_read_quant_array_trie) { BinaryTest<QuantArrayTrieModel>(); } BOOST_AUTO_TEST_CASE(rest_max) { Config config; config.arpa_complain = Config::NONE; config.messages = NULL; RestProbingModel model(TestLocation(), config); State state, out; FullScoreReturn ret(model.FullScore(model.NullContextState(), model.GetVocabulary().Index("."), state)); SLOPPY_CHECK_CLOSE(-0.2705918, ret.rest, 0.001); SLOPPY_CHECK_CLOSE(-0.01916512, model.FullScore(state, model.GetVocabulary().EndSentence(), out).rest, 0.001); } } // namespace } // namespace ngram } // namespace lm
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/flashlight/flashlight/lib/text
coqui_public_repos/STT/native_client/ctcdecode/third_party/flashlight/flashlight/lib/text/decoder/LexiconDecoder.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ #include <stdlib.h> #include <algorithm> #include <cmath> #include <functional> #include <numeric> #include <unordered_map> #include "flashlight/lib/text/decoder/LexiconDecoder.h" namespace fl { namespace lib { namespace text { void LexiconDecoder::decodeBegin() { hyp_.clear(); hyp_.emplace(0, std::vector<LexiconDecoderState>()); /* note: the lm reset itself with :start() */ hyp_[0].emplace_back( 0.0, lm_->start(0), lexicon_->getRoot(), nullptr, sil_, -1); nDecodedFrames_ = 0; nPrunedFrames_ = 0; } void LexiconDecoder::decodeStep(const float* emissions, int T, int N) { int startFrame = nDecodedFrames_ - nPrunedFrames_; // Extend hyp_ buffer if (hyp_.size() < startFrame + T + 2) { for (int i = hyp_.size(); i < startFrame + T + 2; i++) { hyp_.emplace(i, std::vector<LexiconDecoderState>()); } } std::vector<size_t> idx(N); for (int t = 0; t < T; t++) { std::iota(idx.begin(), idx.end(), 0); if (N > opt_.beamSizeToken) { std::partial_sort( idx.begin(), idx.begin() + opt_.beamSizeToken, idx.end(), [&t, &N, &emissions](const size_t& l, const size_t& r) { return emissions[t * N + l] > emissions[t * N + r]; }); } candidatesReset(candidatesBestScore_, candidates_, candidatePtrs_); for (const LexiconDecoderState& prevHyp : hyp_[startFrame + t]) { const TrieNode* prevLex = prevHyp.lex; const int prevIdx = prevHyp.token; const float lexMaxScore = prevLex == lexicon_->getRoot() ? 0 : prevLex->maxScore; /* (1) Try children */ for (int r = 0; r < std::min(opt_.beamSizeToken, N); ++r) { int n = idx[r]; auto iter = prevLex->children.find(n); if (iter == prevLex->children.end()) { continue; } const TrieNodePtr& lex = iter->second; double amScore = emissions[t * N + n]; if (nDecodedFrames_ + t > 0 && opt_.criterionType == CriterionType::ASG) { amScore += transitions_[n * N + prevIdx]; } double score = prevHyp.score + amScore; if (n == sil_) { score += opt_.silScore; } LMStatePtr lmState; double lmScore = 0.; if (isLmToken_) { auto lmStateScorePair = lm_->score(prevHyp.lmState, n); lmState = lmStateScorePair.first; lmScore = lmStateScorePair.second; } // We eat-up a new token if (opt_.criterionType != CriterionType::CTC || prevHyp.prevBlank || n != prevIdx) { if (!lex->children.empty()) { if (!isLmToken_) { lmState = prevHyp.lmState; lmScore = lex->maxScore - lexMaxScore; } candidatesAdd( candidates_, candidatesBestScore_, opt_.beamThreshold, score + opt_.lmWeight * lmScore, lmState, lex.get(), &prevHyp, n, -1, false, // prevBlank prevHyp.amScore + amScore, prevHyp.lmScore + lmScore); } } // If we got a true word for (auto label : lex->labels) { if (prevLex == lexicon_->getRoot() && prevHyp.token == n) { // This is to avoid an situation that, when there is word with // single token spelling (e.g. X -> x) in the lexicon and token `x` // is predicted in several consecutive frames, multiple word `X` // will be emitted. This violates the property of CTC, where // there must be an blank token in between to predict 2 identical // tokens consecutively. continue; } if (!isLmToken_) { auto lmStateScorePair = lm_->score(prevHyp.lmState, label); lmState = lmStateScorePair.first; lmScore = lmStateScorePair.second - lexMaxScore; } candidatesAdd( candidates_, candidatesBestScore_, opt_.beamThreshold, score + opt_.lmWeight * lmScore + opt_.wordScore, lmState, lexicon_->getRoot(), &prevHyp, n, label, false, // prevBlank prevHyp.amScore + amScore, prevHyp.lmScore + lmScore); } // If we got an unknown word if (lex->labels.empty() && (opt_.unkScore > kNegativeInfinity)) { if (!isLmToken_) { auto lmStateScorePair = lm_->score(prevHyp.lmState, unk_); lmState = lmStateScorePair.first; lmScore = lmStateScorePair.second - lexMaxScore; } candidatesAdd( candidates_, candidatesBestScore_, opt_.beamThreshold, score + opt_.lmWeight * lmScore + opt_.unkScore, lmState, lexicon_->getRoot(), &prevHyp, n, unk_, false, // prevBlank prevHyp.amScore + amScore, prevHyp.lmScore + lmScore); } } /* (2) Try same lexicon node */ if (opt_.criterionType != CriterionType::CTC || !prevHyp.prevBlank || prevLex == lexicon_->getRoot()) { int n = prevLex == lexicon_->getRoot() ? sil_ : prevIdx; double amScore = emissions[t * N + n]; if (nDecodedFrames_ + t > 0 && opt_.criterionType == CriterionType::ASG) { amScore += transitions_[n * N + prevIdx]; } double score = prevHyp.score + amScore; if (n == sil_) { score += opt_.silScore; } candidatesAdd( candidates_, candidatesBestScore_, opt_.beamThreshold, score, prevHyp.lmState, prevLex, &prevHyp, n, -1, false, // prevBlank prevHyp.amScore + amScore, prevHyp.lmScore); } /* (3) CTC only, try blank */ if (opt_.criterionType == CriterionType::CTC) { int n = blank_; double amScore = emissions[t * N + n]; candidatesAdd( candidates_, candidatesBestScore_, opt_.beamThreshold, prevHyp.score + amScore, prevHyp.lmState, prevLex, &prevHyp, n, -1, true, // prevBlank prevHyp.amScore + amScore, prevHyp.lmScore); } // finish proposing } candidatesStore( candidates_, candidatePtrs_, hyp_[startFrame + t + 1], opt_.beamSize, candidatesBestScore_ - opt_.beamThreshold, opt_.logAdd, false); updateLMCache(lm_, hyp_[startFrame + t + 1]); } nDecodedFrames_ += T; } void LexiconDecoder::decodeEnd() { candidatesReset(candidatesBestScore_, candidates_, candidatePtrs_); bool hasNiceEnding = false; for (const LexiconDecoderState& prevHyp : hyp_[nDecodedFrames_ - nPrunedFrames_]) { if (prevHyp.lex == lexicon_->getRoot()) { hasNiceEnding = true; break; } } for (const LexiconDecoderState& prevHyp : hyp_[nDecodedFrames_ - nPrunedFrames_]) { const TrieNode* prevLex = prevHyp.lex; const LMStatePtr& prevLmState = prevHyp.lmState; if (!hasNiceEnding || prevHyp.lex == lexicon_->getRoot()) { auto lmStateScorePair = lm_->finish(prevLmState); auto lmScore = lmStateScorePair.second; candidatesAdd( candidates_, candidatesBestScore_, opt_.beamThreshold, prevHyp.score + opt_.lmWeight * lmScore, lmStateScorePair.first, prevLex, &prevHyp, sil_, -1, false, // prevBlank prevHyp.amScore, prevHyp.lmScore + lmScore); } } candidatesStore( candidates_, candidatePtrs_, hyp_[nDecodedFrames_ - nPrunedFrames_ + 1], opt_.beamSize, candidatesBestScore_ - opt_.beamThreshold, opt_.logAdd, true); ++nDecodedFrames_; } std::vector<DecodeResult> LexiconDecoder::getAllFinalHypothesis() const { int finalFrame = nDecodedFrames_ - nPrunedFrames_; if (finalFrame < 1) { return std::vector<DecodeResult>{}; } return getAllHypothesis(hyp_.find(finalFrame)->second, finalFrame); } DecodeResult LexiconDecoder::getBestHypothesis(int lookBack) const { if (nDecodedFrames_ - nPrunedFrames_ - lookBack < 1) { return DecodeResult(); } const LexiconDecoderState* bestNode = findBestAncestor( hyp_.find(nDecodedFrames_ - nPrunedFrames_)->second, lookBack); return getHypothesis(bestNode, nDecodedFrames_ - nPrunedFrames_ - lookBack); } int LexiconDecoder::nHypothesis() const { int finalFrame = nDecodedFrames_ - nPrunedFrames_; return hyp_.find(finalFrame)->second.size(); } int LexiconDecoder::nDecodedFramesInBuffer() const { return nDecodedFrames_ - nPrunedFrames_ + 1; } void LexiconDecoder::prune(int lookBack) { if (nDecodedFrames_ - nPrunedFrames_ - lookBack < 1) { return; // Not enough decoded frames to prune } /* (1) Find the last emitted word in the best path */ const LexiconDecoderState* bestNode = findBestAncestor( hyp_.find(nDecodedFrames_ - nPrunedFrames_)->second, lookBack); if (!bestNode) { return; // Not enough decoded frames to prune } int startFrame = nDecodedFrames_ - nPrunedFrames_ - lookBack; if (startFrame < 1) { return; // Not enough decoded frames to prune } /* (2) Move things from back of hyp_ to front and normalize scores */ pruneAndNormalize(hyp_, startFrame, lookBack); nPrunedFrames_ = nDecodedFrames_ - lookBack; } } // namespace text } // namespace lib } // namespace fl
0
coqui_public_repos/STT
coqui_public_repos/STT/native_client/getopt_win.h
#ifndef __GETOPT_H__ /** * DISCLAIMER * This file is part of the mingw-w64 runtime package. * * The mingw-w64 runtime package and its code is distributed in the hope that it * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Sponsored in part by the Defense Advanced Research Projects * Agency (DARPA) and Air Force Research Laboratory, Air Force * Materiel Command, USAF, under agreement number F39502-99-1-0512. */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #pragma warning(disable:4996); #define __GETOPT_H__ /* All the headers include this file. */ #include <crtdefs.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <windows.h> #ifdef __cplusplus extern "C" { #endif #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ #ifdef REPLACE_GETOPT int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = '?'; /* character checked for validity */ #undef optreset /* see getopt.h */ #define optreset __mingw_optreset int optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #endif //extern int optind; /* index of first non-option in argv */ //extern int optopt; /* single option character, as parsed */ //extern int opterr; /* flag to enable built-in diagnostics... */ // /* (user may set to zero, to suppress) */ // //extern char *optarg; /* pointer to argument of current option */ #define PRINT_ERROR ((opterr) && (*options != ':')) #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ /* return values */ #define BADCH (int)'?' #define BADARG ((*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 #ifndef __CYGWIN__ #define __progname __argv[0] #else extern char __declspec(dllimport) *__progname; #endif #ifdef __CYGWIN__ static char EMSG[] = ""; #else #define EMSG "" #endif static int getopt_internal(int, char * const *, const char *, const struct option *, int *, int); static int parse_long_options(char * const *, const char *, const struct option *, int *, int); static int gcd(int, int); static void permute_args(int, int, int, char * const *); static char *place = EMSG; /* option letter processing */ /* XXX: set optreset to 1 rather than these two */ static int nonopt_start = -1; /* first non option argument (for permute) */ static int nonopt_end = -1; /* first option after non options (for permute) */ /* Error messages */ static const char recargchar[] = "option requires an argument -- %c"; static const char recargstring[] = "option requires an argument -- %s"; static const char ambig[] = "ambiguous option -- %.*s"; static const char noarg[] = "option doesn't take an argument -- %.*s"; static const char illoptchar[] = "unknown option -- %c"; static const char illoptstring[] = "unknown option -- %s"; static void _vwarnx(const char *fmt,va_list ap) { (void)fprintf(stderr,"%s: ",__progname); if (fmt != NULL) (void)vfprintf(stderr,fmt,ap); (void)fprintf(stderr,"\n"); } static void warnx(const char *fmt,...) { va_list ap; va_start(ap,fmt); _vwarnx(fmt,ap); va_end(ap); } /* * Compute the greatest common divisor of a and b. */ static int gcd(int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return (b); } /* * Exchange the block from nonopt_start to nonopt_end with the block * from nonopt_end to opt_end (keeping the same order of arguments * in each block). */ static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char * const *nargv) { int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; /* * compute lengths of blocks and number and size of cycles */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd(nnonopts, nopts); cyclelen = (opt_end - panonopt_start) / ncycle; for (i = 0; i < ncycle; i++) { cstart = panonopt_end+i; pos = cstart; for (j = 0; j < cyclelen; j++) { if (pos >= panonopt_end) pos -= nnonopts; else pos += nopts; swap = nargv[pos]; /* LINTED const cast */ ((char **) nargv)[pos] = nargv[cstart]; /* LINTED const cast */ ((char **)nargv)[cstart] = swap; } } } #ifdef REPLACE_GETOPT /* * getopt -- * Parse argc/argv argument vector. * * [eventually this will replace the BSD getopt] */ int getopt(int nargc, char * const *nargv, const char *options) { /* * We don't pass FLAG_PERMUTE to getopt_internal() since * the BSD getopt(3) (unlike GNU) has never done this. * * Furthermore, since many privileged programs call getopt() * before dropping privileges it makes sense to keep things * as simple (and bug-free) as possible. */ return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); } #endif /* REPLACE_GETOPT */ //extern int getopt(int nargc, char * const *nargv, const char *options); #ifdef _BSD_SOURCE /* * BSD adds the non-standard `optreset' feature, for reinitialisation * of `getopt' parsing. We support this feature, for applications which * proclaim their BSD heritage, before including this header; however, * to maintain portability, developers are advised to avoid it. */ # define optreset __mingw_optreset extern int optreset; #endif #ifdef __cplusplus } #endif /* * POSIX requires the `getopt' API to be specified in `unistd.h'; * thus, `unistd.h' includes this header. However, we do not want * to expose the `getopt_long' or `getopt_long_only' APIs, when * included in this manner. Thus, close the standard __GETOPT_H__ * declarations block, and open an additional __GETOPT_LONG_H__ * specific block, only when *not* __UNISTD_H_SOURCED__, in which * to declare the extended API. */ #endif /* !defined(__GETOPT_H__) */ #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) #define __GETOPT_LONG_H__ #ifdef __cplusplus extern "C" { #endif struct option /* specification for a long form option... */ { const char *name; /* option name, without leading hyphens */ int has_arg; /* does it take an argument? */ int *flag; /* where to save its status, or NULL */ int val; /* its associated status value */ }; enum /* permitted values for its `has_arg' field... */ { no_argument = 0, /* option never takes an argument */ required_argument, /* option always requires an argument */ optional_argument /* option may take an argument */ }; /* * parse_long_options -- * Parse long options in argc/argv argument vector. * Returns -1 if short_too is set and the option does not match long_options. */ static int parse_long_options(char * const *nargv, const char *options, const struct option *long_options, int *idx, int short_too) { char *current_argv, *has_equal; size_t current_argv_len; int i, ambiguous, match; #define IDENTICAL_INTERPRETATION(_x, _y) \ (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ long_options[(_x)].flag == long_options[(_y)].flag && \ long_options[(_x)].val == long_options[(_y)].val) current_argv = place; match = -1; ambiguous = 0; optind++; if ((has_equal = strchr(current_argv, '=')) != NULL) { /* argument found (--option=arg) */ current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen(current_argv); for (i = 0; long_options[i].name; i++) { /* find matching long option */ if (strncmp(current_argv, long_options[i].name, current_argv_len)) continue; if (strlen(long_options[i].name) == current_argv_len) { /* exact match */ match = i; ambiguous = 0; break; } /* * If this is a known short option, don't allow * a partial match of a single character. */ if (short_too && current_argv_len == 1) continue; if (match == -1) /* partial match */ match = i; else if (!IDENTICAL_INTERPRETATION(i, match)) ambiguous = 1; } if (ambiguous) { /* ambiguous abbreviation */ if (PRINT_ERROR) warnx(ambig, (int)current_argv_len, current_argv); optopt = 0; return (BADCH); } if (match != -1) { /* option found */ if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) warnx(noarg, (int)current_argv_len, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; return (BADARG); } if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use next nargv */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' indicates no error * should be generated. */ if (PRINT_ERROR) warnx(recargstring, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; --optind; return (BADARG); } } else { /* unknown option */ if (short_too) { --optind; return (-1); } if (PRINT_ERROR) warnx(illoptstring, current_argv); optopt = 0; return (BADCH); } if (idx) *idx = match; if (long_options[match].flag) { *long_options[match].flag = long_options[match].val; return (0); } else return (long_options[match].val); #undef IDENTICAL_INTERPRETATION } /* * getopt_internal -- * Parse argc/argv argument vector. Called by user level routines. */ static int getopt_internal(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx, int flags) { char *oli; /* option letter list index */ int optchar, short_too; static int posixly_correct = -1; if (options == NULL) return (-1); /* * XXX Some GNU programs (like cvs) set optind to 0 instead of * XXX using optreset. Work around this braindamage. */ if (optind == 0) optind = optreset = 1; /* * Disable GNU extensions if POSIXLY_CORRECT is set or options * string begins with a '+'. * * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or * optreset != 0 for GNU compatibility. */ if (posixly_correct == -1 || optreset != 0) posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); if (*options == '-') flags |= FLAG_ALLARGS; else if (posixly_correct || *options == '+') flags &= ~FLAG_PERMUTE; if (*options == '+' || *options == '-') options++; optarg = NULL; if (optreset) nonopt_start = nonopt_end = -1; start: if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc) { /* end of argument vector */ place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* * If we skipped non-options, set optind * to the first of them. */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr(options, '-') == NULL)) { place = EMSG; /* found non-option */ if (flags & FLAG_ALLARGS) { /* * GNU extension: * return non-option as argument to option 1 */ optarg = nargv[optind++]; return (INORDER); } if (!(flags & FLAG_PERMUTE)) { /* * If no permutation wanted, stop parsing * at first non-option. */ return (-1); } /* do permutation */ if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; /* process next argument */ goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; /* * If we have "-" do nothing, if "--" we are done. */ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; /* * We found an option (--), so if we skipped * non-options, we have to permute. */ if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } } /* * Check long options if: * 1) we were passed some * 2) the arg is not just "-" * 3) either the arg starts with -- we are getopt_long_only() */ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { short_too = 0; if (*place == '-') place++; /* --foo long option */ else if (*place != ':' && strchr(options, *place) != NULL) short_too = 1; /* could be short option too */ optchar = parse_long_options(nargv, options, long_options, idx, short_too); if (optchar != -1) { place = EMSG; return (optchar); } } if ((optchar = (int)*place++) == (int)':' || (optchar == (int)'-' && *place != '\0') || (oli = (char*)strchr(options, optchar)) == NULL) { /* * If the user specified "-" and '-' isn't listed in * options, return -1 (non-option) as per POSIX. * Otherwise, it is an unknown option character (or ':'). */ if (optchar == (int)'-' && *place == '\0') return (-1); if (!*place) ++optind; if (PRINT_ERROR) warnx(illoptchar, optchar); optopt = optchar; return (BADCH); } if (long_options != NULL && optchar == 'W' && oli[1] == ';') { /* -W long-option */ if (*place) /* no space */ /* NOTHING */; else if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); } else /* white space */ place = nargv[optind]; optchar = parse_long_options(nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } if (*++oli != ':') { /* doesn't take argument */ if (!*place) ++optind; } else { /* takes (optional) argument */ optarg = NULL; if (*place) /* no white space */ optarg = place; else if (oli[1] != ':') { /* arg not optional */ if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); } else optarg = nargv[optind]; } place = EMSG; ++optind; } /* dump back option letter */ return (optchar); } /* * getopt_long -- * Parse argc/argv argument vector. */ int getopt_long(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE)); } /* * getopt_long_only -- * Parse argc/argv argument vector. */ int getopt_long_only(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE|FLAG_LONGONLY)); } //extern int getopt_long(int nargc, char * const *nargv, const char *options, // const struct option *long_options, int *idx); //extern int getopt_long_only(int nargc, char * const *nargv, const char *options, // const struct option *long_options, int *idx); /* * Previous MinGW implementation had... */ #ifndef HAVE_DECL_GETOPT /* * ...for the long form API only; keep this for compatibility. */ # define HAVE_DECL_GETOPT 1 #endif #ifdef __cplusplus } #endif #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */
0
coqui_public_repos/STT/native_client/ctcdecode/third_party
coqui_public_repos/STT/native_client/ctcdecode/third_party/object_pool/unique_ptr.h
#ifndef GODEFV_MEMORY_ALLOCATED_UNIQUE_PTR_H #define GODEFV_MEMORY_ALLOCATED_UNIQUE_PTR_H #include <memory> namespace godefv{ //! A deleter to deallocate memory which have been allocated by the given allocator. template<class Allocator> struct allocator_deleter_t { allocator_deleter_t(Allocator const& allocator) : mAllocator{ allocator } {} void operator()(typename Allocator::value_type* ptr) { mAllocator.deallocate(ptr, 1); } private: Allocator mAllocator; }; //! A smart pointer like std::unique_ptr but templated on an allocator instead of a deleter. //! The deleter is deduced from the given allocator. template<class T, class Allocator = std::allocator<T>> struct unique_ptr_t : public std::unique_ptr<T, allocator_deleter_t<Allocator>> { using base_t = std::unique_ptr<T, allocator_deleter_t<Allocator>>; unique_ptr_t(Allocator allocator = Allocator{}) : base_t{ allocator.allocate(1), allocator_deleter_t<Allocator>{ allocator } } {} }; } // namespace godefv #endif // GODEFV_MEMORY_ALLOCATED_UNIQUE_PTR_H
0
coqui_public_repos/STT/native_client
coqui_public_repos/STT/native_client/java/gradle.properties
# Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx1536m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true
0
coqui_public_repos/STT/native_client/java
coqui_public_repos/STT/native_client/java/.idea/misc.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="NullableNotNullManager"> <option name="myDefaultNullable" value="android.support.annotation.Nullable" /> <option name="myDefaultNotNull" value="android.support.annotation.NonNull" /> <option name="myNullables"> <value> <list size="7"> <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" /> <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" /> <item index="2" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" /> <item index="3" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" /> <item index="4" class="java.lang.String" itemvalue="android.support.annotation.Nullable" /> <item index="5" class="java.lang.String" itemvalue="androidx.annotation.Nullable" /> <item index="6" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNullable" /> </list> </value> </option> <option name="myNotNulls"> <value> <list size="6"> <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" /> <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" /> <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" /> <item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" /> <item index="4" class="java.lang.String" itemvalue="androidx.annotation.NonNull" /> <item index="5" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNonNull" /> </list> </value> </option> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/build/classes" /> </component> <component name="ProjectType"> <option name="id" value="Android" /> </component> </project>
0
coqui_public_repos/STT/native_client/dotnet/STTWPF
coqui_public_repos/STT/native_client/dotnet/STTWPF/Properties/Settings.settings
<?xml version='1.0' encoding='utf-8'?> <SettingsFile xmlns="uri:settings" CurrentProfile="(Default)"> <Profiles> <Profile Name="(Default)" /> </Profiles> <Settings /> </SettingsFile>
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/script/encode.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/script/fst-class.h> #include <fst/encode.h> #include <fst/script/encode.h> #include <fst/script/script-impl.h> namespace fst { namespace script { void Encode(MutableFstClass *fst, uint32 flags, bool reuse_encoder, const string &coder_fname) { EncodeArgs1 args(fst, flags, reuse_encoder, coder_fname); Apply<Operation<EncodeArgs1>>("Encode", fst->ArcType(), &args); } void Encode(MutableFstClass *fst, EncodeMapperClass *encoder) { if (!internal::ArcTypesMatch(*fst, *encoder, "Encode")) { fst->SetProperties(kError, kError); return; } EncodeArgs2 args(fst, encoder); Apply<Operation<EncodeArgs2>>("Encode", fst->ArcType(), &args); } REGISTER_FST_OPERATION(Encode, StdArc, EncodeArgs1); REGISTER_FST_OPERATION(Encode, LogArc, EncodeArgs1); REGISTER_FST_OPERATION(Encode, Log64Arc, EncodeArgs1); REGISTER_FST_OPERATION(Encode, StdArc, EncodeArgs2); REGISTER_FST_OPERATION(Encode, LogArc, EncodeArgs2); REGISTER_FST_OPERATION(Encode, Log64Arc, EncodeArgs2); } // namespace script } // namespace fst
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-transcribe_16k-linux-amd64-py36m-opt.yml
build: template_file: test-linux-opt-base.tyml dependencies: - "test-training_16k-linux-amd64-py36m-opt" system_setup: > apt-get -qq update && apt-get -qq -y install ${training.packages_xenial.apt} ${python.packages_xenial.apt} args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-transcribe-tests.sh 3.6.10:m 16k" workerType: "${docker.dsTests}" metadata: name: "DeepSpeech Linux AMD64 CPU 16kHz transcribe Py3.6" description: "Transcribe a DeepSpeech LDC93S1 model for Linux/AMD64 16kHz Python 3.6, CPU only, optimized version"
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/compact/compact64_string-fst.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/fst.h> #include <fst/compact-fst.h> namespace fst { static FstRegisterer<CompactStringFst<StdArc, uint64>> CompactStringFst_StdArc_uint64_registerer; static FstRegisterer<CompactStringFst<LogArc, uint64>> CompactStringFst_LogArc_uint64_registerer; } // namespace fst
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/extensions/far/farequal.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Tests if two Far files contains the same (key,fst) pairs. #include <string> #include <fst/flags.h> #include <fst/extensions/far/farscript.h> #include <fst/extensions/far/getters.h> DEFINE_string(begin_key, "", "First key to extract (def: first key in archive)"); DEFINE_string(end_key, "", "Last key to extract (def: last key in archive)"); DEFINE_double(delta, fst::kDelta, "Comparison/quantization delta"); int main(int argc, char **argv) { namespace s = fst::script; string usage = "Compares the FSTs in two FST archives for equality."; usage += "\n\n Usage:"; usage += argv[0]; usage += " in1.far in2.far"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); s::ExpandArgs(argc, argv, &argc, &argv); if (argc != 3) { ShowUsage(); return 1; } const auto arc_type = s::LoadArcTypeFromFar(argv[1]); if (arc_type.empty()) return 1; bool result = s::FarEqual(argv[1], argv[2], arc_type, FLAGS_delta, FLAGS_begin_key, FLAGS_end_key); if (!result) VLOG(1) << "FARs are not equal."; return result ? 0 : 2; }
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstcompile-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Creates binary FSTs from simple text format used by AT&T. #include <cstring> #include <fstream> #include <istream> #include <memory> #include <string> #include <fst/flags.h> #include <fst/log.h> #include <fst/script/compile.h> DECLARE_bool(acceptor); DECLARE_string(arc_type); DECLARE_string(fst_type); DECLARE_string(isymbols); DECLARE_string(osymbols); DECLARE_string(ssymbols); DECLARE_bool(keep_isymbols); DECLARE_bool(keep_osymbols); DECLARE_bool(keep_state_numbering); DECLARE_bool(allow_negative_labels); int fstcompile_main(int argc, char **argv) { namespace s = fst::script; using fst::SymbolTable; using fst::SymbolTableTextOptions; string usage = "Creates binary FSTs from simple text format.\n\n Usage: "; usage += argv[0]; usage += " [text.fst [binary.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } string source = "standard input"; std::ifstream fstrm; if (argc > 1 && strcmp(argv[1], "-") != 0) { fstrm.open(argv[1]); if (!fstrm) { LOG(ERROR) << argv[0] << ": Open failed, file = " << argv[1]; return 1; } source = argv[1]; } std::istream &istrm = fstrm.is_open() ? fstrm : std::cin; const SymbolTableTextOptions opts(FLAGS_allow_negative_labels); std::unique_ptr<const SymbolTable> isyms; if (!FLAGS_isymbols.empty()) { isyms.reset(SymbolTable::ReadText(FLAGS_isymbols, opts)); if (!isyms) return 1; } std::unique_ptr<const SymbolTable> osyms; if (!FLAGS_osymbols.empty()) { osyms.reset(SymbolTable::ReadText(FLAGS_osymbols, opts)); if (!osyms) return 1; } std::unique_ptr<const SymbolTable> ssyms; if (!FLAGS_ssymbols.empty()) { ssyms.reset(SymbolTable::ReadText(FLAGS_ssymbols)); if (!ssyms) return 1; } const string dest = argc > 2 ? argv[2] : ""; s::CompileFst(istrm, source, dest, FLAGS_fst_type, FLAGS_arc_type, isyms.get(), osyms.get(), ssyms.get(), FLAGS_acceptor, FLAGS_keep_isymbols, FLAGS_keep_osymbols, FLAGS_keep_state_numbering, FLAGS_allow_negative_labels); return 0; }
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/script/rmepsilon.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_RMEPSILON_H_ #define FST_SCRIPT_RMEPSILON_H_ #include <utility> #include <vector> #include <fst/queue.h> #include <fst/rmepsilon.h> #include <fst/script/fst-class.h> #include <fst/script/shortest-distance.h> #include <fst/script/weight-class.h> namespace fst { namespace script { struct RmEpsilonOptions : public ShortestDistanceOptions { const bool connect; const WeightClass &weight_threshold; const int64_t state_threshold; RmEpsilonOptions(QueueType queue_type, bool connect, const WeightClass &weight_threshold, int64_t state_threshold = kNoStateId, float delta = kDelta) : ShortestDistanceOptions(queue_type, EPSILON_ARC_FILTER, kNoStateId, delta), connect(connect), weight_threshold(weight_threshold), state_threshold(state_threshold) {} }; namespace internal { // Code to implement switching on queue types. template <class Arc, class Queue> void RmEpsilon(MutableFst<Arc> *fst, std::vector<typename Arc::Weight> *distance, const RmEpsilonOptions &opts, Queue *queue) { using Weight = typename Arc::Weight; const fst::RmEpsilonOptions<Arc, Queue> ropts( queue, opts.delta, opts.connect, *opts.weight_threshold.GetWeight<Weight>(), opts.state_threshold); RmEpsilon(fst, distance, ropts); } template <class Arc> void RmEpsilon(MutableFst<Arc> *fst, const RmEpsilonOptions &opts) { using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; std::vector<Weight> distance; switch (opts.queue_type) { case AUTO_QUEUE: { AutoQueue<StateId> queue(*fst, &distance, EpsilonArcFilter<Arc>()); RmEpsilon(fst, &distance, opts, &queue); return; } case FIFO_QUEUE: { FifoQueue<StateId> queue; RmEpsilon(fst, &distance, opts, &queue); return; } case LIFO_QUEUE: { LifoQueue<StateId> queue; RmEpsilon(fst, &distance, opts, &queue); return; } case SHORTEST_FIRST_QUEUE: { NaturalShortestFirstQueue<StateId, Weight> queue(distance); RmEpsilon(fst, &distance, opts, &queue); return; } case STATE_ORDER_QUEUE: { StateOrderQueue<StateId> queue; RmEpsilon(fst, &distance, opts, &queue); return; } case TOP_ORDER_QUEUE: { TopOrderQueue<StateId> queue(*fst, EpsilonArcFilter<Arc>()); internal::RmEpsilon(fst, &distance, opts, &queue); return; } default: { FSTERROR() << "RmEpsilon: Unknown queue type: " << opts.queue_type; fst->SetProperties(kError, kError); return; } } } } // namespace internal using RmEpsilonArgs = std::pair<MutableFstClass *, const RmEpsilonOptions &>; template <class Arc> void RmEpsilon(RmEpsilonArgs *args) { MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>(); const auto &opts = std::get<1>(*args); internal::RmEpsilon(fst, opts); } void RmEpsilon(MutableFstClass *fst, const RmEpsilonOptions &opts); } // namespace script } // namespace fst #endif // FST_SCRIPT_RMEPSILON_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/pdt/info.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Prints information about a PDT. #ifndef FST_EXTENSIONS_PDT_INFO_H_ #define FST_EXTENSIONS_PDT_INFO_H_ #include <unordered_map> #include <unordered_set> #include <vector> #include <fst/extensions/pdt/pdt.h> #include <fst/fst.h> namespace fst { // Compute various information about PDTs. template <class Arc> class PdtInfo { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; PdtInfo(const Fst<Arc> &fst, const std::vector<std::pair<Label, Label>> &parents); const string &FstType() const { return fst_type_; } const string &ArcType() const { return Arc::Type(); } int64 NumStates() const { return nstates_; } int64 NumArcs() const { return narcs_; } int64 NumOpenParens() const { return nopen_parens_; } int64 NumCloseParens() const { return nclose_parens_; } int64 NumUniqueOpenParens() const { return nuniq_open_parens_; } int64 NumUniqueCloseParens() const { return nuniq_close_parens_; } int64 NumOpenParenStates() const { return nopen_paren_states_; } int64 NumCloseParenStates() const { return nclose_paren_states_; } private: string fst_type_; int64 nstates_; int64 narcs_; int64 nopen_parens_; int64 nclose_parens_; int64 nuniq_open_parens_; int64 nuniq_close_parens_; int64 nopen_paren_states_; int64 nclose_paren_states_; }; template <class Arc> PdtInfo<Arc>::PdtInfo( const Fst<Arc> &fst, const std::vector<std::pair<typename Arc::Label, typename Arc::Label>> &parens) : fst_type_(fst.Type()), nstates_(0), narcs_(0), nopen_parens_(0), nclose_parens_(0), nuniq_open_parens_(0), nuniq_close_parens_(0), nopen_paren_states_(0), nclose_paren_states_(0) { std::unordered_map<Label, size_t> paren_map; std::unordered_set<Label> paren_set; std::unordered_set<StateId> open_paren_state_set; std::unordered_set<StateId> close_paren_state_set; for (size_t i = 0; i < parens.size(); ++i) { const auto &pair = parens[i]; paren_map[pair.first] = i; paren_map[pair.second] = i; } for (StateIterator<Fst<Arc>> siter(fst); !siter.Done(); siter.Next()) { ++nstates_; const auto s = siter.Value(); for (ArcIterator<Fst<Arc>> aiter(fst, s); !aiter.Done(); aiter.Next()) { const auto &arc = aiter.Value(); ++narcs_; const auto it = paren_map.find(arc.ilabel); if (it != paren_map.end()) { const auto open_paren = parens[it->second].first; const auto close_paren = parens[it->second].second; if (arc.ilabel == open_paren) { ++nopen_parens_; if (!paren_set.count(open_paren)) { ++nuniq_open_parens_; paren_set.insert(open_paren); } if (!open_paren_state_set.count(arc.nextstate)) { ++nopen_paren_states_; open_paren_state_set.insert(arc.nextstate); } } else { ++nclose_parens_; if (!paren_set.count(close_paren)) { ++nuniq_close_parens_; paren_set.insert(close_paren); } if (!close_paren_state_set.count(s)) { ++nclose_paren_states_; close_paren_state_set.insert(s); } } } } } } template <class Arc> void PrintPdtInfo(const PdtInfo<Arc> &info) { const auto old = std::cout.setf(std::ios::left); std::cout.width(50); std::cout << "fst type" << info.FstType() << std::endl; std::cout.width(50); std::cout << "arc type" << info.ArcType() << std::endl; std::cout.width(50); std::cout << "# of states" << info.NumStates() << std::endl; std::cout.width(50); std::cout << "# of arcs" << info.NumArcs() << std::endl; std::cout.width(50); std::cout << "# of open parentheses" << info.NumOpenParens() << std::endl; std::cout.width(50); std::cout << "# of close parentheses" << info.NumCloseParens() << std::endl; std::cout.width(50); std::cout << "# of unique open parentheses" << info.NumUniqueOpenParens() << std::endl; std::cout.width(50); std::cout << "# of unique close parentheses" << info.NumUniqueCloseParens() << std::endl; std::cout.width(50); std::cout << "# of open parenthesis dest. states" << info.NumOpenParenStates() << std::endl; std::cout.width(50); std::cout << "# of close parenthesis source states" << info.NumCloseParenStates() << std::endl; std::cout.setf(old); } } // namespace fst #endif // FST_EXTENSIONS_PDT_INFO_H_
0
coqui_public_repos/STT/native_client/kenlm/lm/common
coqui_public_repos/STT/native_client/kenlm/lm/common/test_data/toy1.arpa
\data\ ngram 1=6 ngram 2=7 ngram 3=6 \1-grams: -1 <unk> 0 0 <s> -0.30103 -0.6146491 a -0.30103 -0.6146491 </s> 0 -0.7659168 c -0.30103 -0.6146491 b -0.30103 \2-grams: -0.4301247 <s> a -0.30103 -0.4301247 a a -0.30103 -0.20660876 c </s> 0 -0.5404639 b </s> 0 -0.4740302 <s> c -0.30103 -0.4301247 a b -0.30103 -0.3422159 b b -0.47712123 \3-grams: -0.1638568 <s> a a -0.09113217 <s> c </s> -0.7462621 b b </s> -0.1638568 a a b -0.13823806 a b b -0.13375957 b b b \end\
0
coqui_public_repos/TTS/TTS/vc/modules/freevc
coqui_public_repos/TTS/TTS/vc/modules/freevc/wavlm/wavlm.py
# -------------------------------------------------------- # WavLM: Large-Scale Self-Supervised Pre-training for Full Stack Speech Processing (https://arxiv.org/abs/2110.13900.pdf) # Github source: https://github.com/microsoft/unilm/tree/master/wavlm # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Based on fairseq code bases # https://github.com/pytorch/fairseq # -------------------------------------------------------- import logging import math from typing import List, Optional, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import LayerNorm from TTS.vc.modules.freevc.wavlm.modules import ( Fp32GroupNorm, Fp32LayerNorm, GLU_Linear, GradMultiply, MultiheadAttention, SamePad, TransposeLast, get_activation_fn, init_bert_params, ) logger = logging.getLogger(__name__) def compute_mask_indices( shape: Tuple[int, int], padding_mask: Optional[torch.Tensor], mask_prob: float, mask_length: int, mask_type: str = "static", mask_other: float = 0.0, min_masks: int = 0, no_overlap: bool = False, min_space: int = 0, ) -> np.ndarray: """ Computes random mask spans for a given shape Args: shape: the the shape for which to compute masks. should be of size 2 where first element is batch size and 2nd is timesteps padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by number of timesteps divided by length of mask span to mask approximately this percentage of all elements. however due to overlaps, the actual number will be smaller (unless no_overlap is True) mask_type: how to compute mask lengths static = fixed size uniform = sample from uniform distribution [mask_other, mask_length*2] normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element poisson = sample from possion distribution with lambda = mask length min_masks: minimum number of masked spans no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans """ bsz, all_sz = shape mask = np.full((bsz, all_sz), False) all_num_mask = int( # add a random number for probabilistic rounding mask_prob * all_sz / float(mask_length) + np.random.rand() ) all_num_mask = max(min_masks, all_num_mask) mask_idcs = [] for i in range(bsz): if padding_mask is not None: sz = all_sz - padding_mask[i].long().sum().item() num_mask = int( # add a random number for probabilistic rounding mask_prob * sz / float(mask_length) + np.random.rand() ) num_mask = max(min_masks, num_mask) else: sz = all_sz num_mask = all_num_mask if mask_type == "static": lengths = np.full(num_mask, mask_length) elif mask_type == "uniform": lengths = np.random.randint(mask_other, mask_length * 2 + 1, size=num_mask) elif mask_type == "normal": lengths = np.random.normal(mask_length, mask_other, size=num_mask) lengths = [max(1, int(round(x))) for x in lengths] elif mask_type == "poisson": lengths = np.random.poisson(mask_length, size=num_mask) lengths = [int(round(x)) for x in lengths] else: raise Exception("unknown mask selection " + mask_type) if sum(lengths) == 0: lengths[0] = min(mask_length, sz - 1) if no_overlap: mask_idc = [] def arrange(s, e, length, keep_length): span_start = np.random.randint(s, e - length) mask_idc.extend(span_start + i for i in range(length)) new_parts = [] if span_start - s - min_space >= keep_length: new_parts.append((s, span_start - min_space + 1)) if e - span_start - keep_length - min_space > keep_length: new_parts.append((span_start + length + min_space, e)) return new_parts parts = [(0, sz)] min_length = min(lengths) for length in sorted(lengths, reverse=True): lens = np.fromiter( (e - s if e - s >= length + min_space else 0 for s, e in parts), np.int, ) l_sum = np.sum(lens) if l_sum == 0: break probs = lens / np.sum(lens) c = np.random.choice(len(parts), p=probs) s, e = parts.pop(c) parts.extend(arrange(s, e, length, min_length)) mask_idc = np.asarray(mask_idc) else: min_len = min(lengths) if sz - min_len <= num_mask: min_len = sz - num_mask - 1 mask_idc = np.random.choice(sz - min_len, num_mask, replace=False) mask_idc = np.asarray([mask_idc[j] + offset for j in range(len(mask_idc)) for offset in range(lengths[j])]) mask_idcs.append(np.unique(mask_idc[mask_idc < sz])) min_len = min([len(m) for m in mask_idcs]) for i, mask_idc in enumerate(mask_idcs): if len(mask_idc) > min_len: mask_idc = np.random.choice(mask_idc, min_len, replace=False) mask[i, mask_idc] = True return mask class WavLMConfig: def __init__(self, cfg=None): self.extractor_mode: str = "default" # mode for feature extractor. default has a single group norm with d groups in the first conv block, whereas layer_norm has layer norms in every block (meant to use with normalize=True) self.encoder_layers: int = 12 # num encoder layers in the transformer self.encoder_embed_dim: int = 768 # encoder embedding dimension self.encoder_ffn_embed_dim: int = 3072 # encoder embedding dimension for FFN self.encoder_attention_heads: int = 12 # num encoder attention heads self.activation_fn: str = "gelu" # activation function to use self.layer_norm_first: bool = False # apply layernorm first in the transformer self.conv_feature_layers: str = "[(512,10,5)] + [(512,3,2)] * 4 + [(512,2,2)] * 2" # string describing convolutional feature extraction layers in form of a python list that contains [(dim, kernel_size, stride), ...] self.conv_bias: bool = False # include bias in conv encoder self.feature_grad_mult: float = 1.0 # multiply feature extractor var grads by this self.normalize: bool = False # normalize input to have 0 mean and unit variance during training # dropouts self.dropout: float = 0.1 # dropout probability for the transformer self.attention_dropout: float = 0.1 # dropout probability for attention weights self.activation_dropout: float = 0.0 # dropout probability after activation in FFN self.encoder_layerdrop: float = 0.0 # probability of dropping a tarnsformer layer self.dropout_input: float = 0.0 # dropout to apply to the input (after feat extr) self.dropout_features: float = 0.0 # dropout to apply to the features (after feat extr) # masking self.mask_length: int = 10 # mask length self.mask_prob: float = 0.65 # probability of replacing a token with mask self.mask_selection: str = "static" # how to choose mask length self.mask_other: float = ( 0 # secondary mask argument (used for more complex distributions), see help in compute_mask_indicesh ) self.no_mask_overlap: bool = False # whether to allow masks to overlap self.mask_min_space: int = 1 # min space between spans (if no overlap is enabled) # channel masking self.mask_channel_length: int = 10 # length of the mask for features (channels) self.mask_channel_prob: float = 0.0 # probability of replacing a feature with 0 self.mask_channel_selection: str = "static" # how to choose mask length for channel masking self.mask_channel_other: float = ( 0 # secondary mask argument (used for more complex distributions), see help in compute_mask_indices ) self.no_mask_channel_overlap: bool = False # whether to allow channel masks to overlap self.mask_channel_min_space: int = 1 # min space between spans (if no overlap is enabled) # positional embeddings self.conv_pos: int = 128 # number of filters for convolutional positional embeddings self.conv_pos_groups: int = 16 # number of groups for convolutional positional embedding # relative position embedding self.relative_position_embedding: bool = False # apply relative position embedding self.num_buckets: int = 320 # number of buckets for relative position embedding self.max_distance: int = 1280 # maximum distance for relative position embedding self.gru_rel_pos: bool = False # apply gated relative position embedding if cfg is not None: self.update(cfg) def update(self, cfg: dict): self.__dict__.update(cfg) class WavLM(nn.Module): def __init__( self, cfg: WavLMConfig, ) -> None: super().__init__() logger.info(f"WavLM Config: {cfg.__dict__}") self.cfg = cfg feature_enc_layers = eval(cfg.conv_feature_layers) self.embed = feature_enc_layers[-1][0] self.feature_extractor = ConvFeatureExtractionModel( conv_layers=feature_enc_layers, dropout=0.0, mode=cfg.extractor_mode, conv_bias=cfg.conv_bias, ) self.post_extract_proj = ( nn.Linear(self.embed, cfg.encoder_embed_dim) if self.embed != cfg.encoder_embed_dim else None ) self.mask_prob = cfg.mask_prob self.mask_selection = cfg.mask_selection self.mask_other = cfg.mask_other self.mask_length = cfg.mask_length self.no_mask_overlap = cfg.no_mask_overlap self.mask_min_space = cfg.mask_min_space self.mask_channel_prob = cfg.mask_channel_prob self.mask_channel_selection = cfg.mask_channel_selection self.mask_channel_other = cfg.mask_channel_other self.mask_channel_length = cfg.mask_channel_length self.no_mask_channel_overlap = cfg.no_mask_channel_overlap self.mask_channel_min_space = cfg.mask_channel_min_space self.dropout_input = nn.Dropout(cfg.dropout_input) self.dropout_features = nn.Dropout(cfg.dropout_features) self.feature_grad_mult = cfg.feature_grad_mult self.mask_emb = nn.Parameter(torch.FloatTensor(cfg.encoder_embed_dim).uniform_()) self.encoder = TransformerEncoder(cfg) self.layer_norm = LayerNorm(self.embed) def apply_mask(self, x, padding_mask): B, T, C = x.shape if self.mask_prob > 0: mask_indices = compute_mask_indices( (B, T), padding_mask, self.mask_prob, self.mask_length, self.mask_selection, self.mask_other, min_masks=2, no_overlap=self.no_mask_overlap, min_space=self.mask_min_space, ) mask_indices = torch.from_numpy(mask_indices).to(x.device) x[mask_indices] = self.mask_emb else: mask_indices = None if self.mask_channel_prob > 0: mask_channel_indices = compute_mask_indices( (B, C), None, self.mask_channel_prob, self.mask_channel_length, self.mask_channel_selection, self.mask_channel_other, no_overlap=self.no_mask_channel_overlap, min_space=self.mask_channel_min_space, ) mask_channel_indices = torch.from_numpy(mask_channel_indices).to(x.device).unsqueeze(1).expand(-1, T, -1) x[mask_channel_indices] = 0 return x, mask_indices def forward_padding_mask( self, features: torch.Tensor, padding_mask: torch.Tensor, ) -> torch.Tensor: extra = padding_mask.size(1) % features.size(1) if extra > 0: padding_mask = padding_mask[:, :-extra] padding_mask = padding_mask.view(padding_mask.size(0), features.size(1), -1) # padding_mask = padding_mask.all(-1) padding_mask = padding_mask.any(-1) return padding_mask def extract_features( self, source: torch.Tensor, padding_mask: Optional[torch.Tensor] = None, mask: bool = False, ret_conv: bool = False, output_layer: Optional[int] = None, ret_layer_results: bool = False, ): if self.feature_grad_mult > 0: features = self.feature_extractor(source) if self.feature_grad_mult != 1.0: features = GradMultiply.apply(features, self.feature_grad_mult) else: with torch.no_grad(): features = self.feature_extractor(source) features = features.transpose(1, 2) features = self.layer_norm(features) if padding_mask is not None: padding_mask = self.forward_padding_mask(features, padding_mask) if self.post_extract_proj is not None: features = self.post_extract_proj(features) features = self.dropout_input(features) if mask: x, mask_indices = self.apply_mask(features, padding_mask) else: x = features # feature: (B, T, D), float # target: (B, T), long # x: (B, T, D), float # padding_mask: (B, T), bool # mask_indices: (B, T), bool x, layer_results = self.encoder( x, padding_mask=padding_mask, layer=None if output_layer is None else output_layer - 1 ) res = {"x": x, "padding_mask": padding_mask, "features": features, "layer_results": layer_results} feature = res["features"] if ret_conv else res["x"] if ret_layer_results: feature = (feature, res["layer_results"]) return feature, res["padding_mask"] class ConvFeatureExtractionModel(nn.Module): def __init__( self, conv_layers: List[Tuple[int, int, int]], dropout: float = 0.0, mode: str = "default", conv_bias: bool = False, conv_type: str = "default", ): super().__init__() assert mode in {"default", "layer_norm"} def block( n_in, n_out, k, stride, is_layer_norm=False, is_group_norm=False, conv_bias=False, ): def make_conv(): conv = nn.Conv1d(n_in, n_out, k, stride=stride, bias=conv_bias) nn.init.kaiming_normal_(conv.weight) return conv assert (is_layer_norm and is_group_norm) == False, "layer norm and group norm are exclusive" if is_layer_norm: return nn.Sequential( make_conv(), nn.Dropout(p=dropout), nn.Sequential( TransposeLast(), Fp32LayerNorm(dim, elementwise_affine=True), TransposeLast(), ), nn.GELU(), ) elif is_group_norm: return nn.Sequential( make_conv(), nn.Dropout(p=dropout), Fp32GroupNorm(dim, dim, affine=True), nn.GELU(), ) else: return nn.Sequential(make_conv(), nn.Dropout(p=dropout), nn.GELU()) self.conv_type = conv_type if self.conv_type == "default": in_d = 1 self.conv_layers = nn.ModuleList() for i, cl in enumerate(conv_layers): assert len(cl) == 3, "invalid conv definition: " + str(cl) (dim, k, stride) = cl self.conv_layers.append( block( in_d, dim, k, stride, is_layer_norm=mode == "layer_norm", is_group_norm=mode == "default" and i == 0, conv_bias=conv_bias, ) ) in_d = dim elif self.conv_type == "conv2d": in_d = 1 self.conv_layers = nn.ModuleList() for i, cl in enumerate(conv_layers): assert len(cl) == 3 (dim, k, stride) = cl self.conv_layers.append(torch.nn.Conv2d(in_d, dim, k, stride)) self.conv_layers.append(torch.nn.ReLU()) in_d = dim elif self.conv_type == "custom": in_d = 1 idim = 80 self.conv_layers = nn.ModuleList() for i, cl in enumerate(conv_layers): assert len(cl) == 3 (dim, k, stride) = cl self.conv_layers.append(torch.nn.Conv2d(in_d, dim, k, stride, padding=1)) self.conv_layers.append(torch.nn.LayerNorm([dim, idim])) self.conv_layers.append(torch.nn.ReLU()) in_d = dim if (i + 1) % 2 == 0: self.conv_layers.append(torch.nn.MaxPool2d(2, stride=2, ceil_mode=True)) idim = int(math.ceil(idim / 2)) else: pass def forward(self, x, mask=None): # BxT -> BxCxT x = x.unsqueeze(1) if self.conv_type == "custom": for conv in self.conv_layers: if isinstance(conv, nn.LayerNorm): x = x.transpose(1, 2) x = conv(x).transpose(1, 2) else: x = conv(x) x = x.transpose(2, 3).contiguous() x = x.view(x.size(0), -1, x.size(-1)) else: for conv in self.conv_layers: x = conv(x) if self.conv_type == "conv2d": b, c, t, f = x.size() x = x.transpose(2, 3).contiguous().view(b, c * f, t) return x class TransformerEncoder(nn.Module): def __init__(self, args): super().__init__() self.dropout = args.dropout self.embedding_dim = args.encoder_embed_dim self.pos_conv = nn.Conv1d( self.embedding_dim, self.embedding_dim, kernel_size=args.conv_pos, padding=args.conv_pos // 2, groups=args.conv_pos_groups, ) dropout = 0 std = math.sqrt((4 * (1.0 - dropout)) / (args.conv_pos * self.embedding_dim)) nn.init.normal_(self.pos_conv.weight, mean=0, std=std) nn.init.constant_(self.pos_conv.bias, 0) self.pos_conv = nn.utils.parametrizations.weight_norm(self.pos_conv, name="weight", dim=2) self.pos_conv = nn.Sequential(self.pos_conv, SamePad(args.conv_pos), nn.GELU()) if hasattr(args, "relative_position_embedding"): self.relative_position_embedding = args.relative_position_embedding self.num_buckets = args.num_buckets self.max_distance = args.max_distance else: self.relative_position_embedding = False self.num_buckets = 0 self.max_distance = 0 self.layers = nn.ModuleList( [ TransformerSentenceEncoderLayer( embedding_dim=self.embedding_dim, ffn_embedding_dim=args.encoder_ffn_embed_dim, num_attention_heads=args.encoder_attention_heads, dropout=self.dropout, attention_dropout=args.attention_dropout, activation_dropout=args.activation_dropout, activation_fn=args.activation_fn, layer_norm_first=args.layer_norm_first, has_relative_attention_bias=(self.relative_position_embedding and i == 0), num_buckets=self.num_buckets, max_distance=self.max_distance, gru_rel_pos=args.gru_rel_pos, ) for i in range(args.encoder_layers) ] ) self.layer_norm_first = args.layer_norm_first self.layer_norm = LayerNorm(self.embedding_dim) self.layerdrop = args.encoder_layerdrop self.apply(init_bert_params) def forward(self, x, padding_mask=None, streaming_mask=None, layer=None): x, layer_results = self.extract_features(x, padding_mask, streaming_mask, layer) if self.layer_norm_first and layer is None: x = self.layer_norm(x) return x, layer_results def extract_features(self, x, padding_mask=None, streaming_mask=None, tgt_layer=None): if padding_mask is not None: x[padding_mask] = 0 x_conv = self.pos_conv(x.transpose(1, 2)) x_conv = x_conv.transpose(1, 2) x += x_conv if not self.layer_norm_first: x = self.layer_norm(x) x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) layer_results = [] z = None if tgt_layer is not None: layer_results.append((x, z)) r = None pos_bias = None for i, layer in enumerate(self.layers): dropout_probability = np.random.random() if not self.training or (dropout_probability > self.layerdrop): x, z, pos_bias = layer( x, self_attn_padding_mask=padding_mask, need_weights=False, self_attn_mask=streaming_mask, pos_bias=pos_bias, ) if tgt_layer is not None: layer_results.append((x, z)) if i == tgt_layer: r = x break if r is not None: x = r # T x B x C -> B x T x C x = x.transpose(0, 1) return x, layer_results class TransformerSentenceEncoderLayer(nn.Module): """ Implements a Transformer Encoder Layer used in BERT/XLM style pre-trained models. """ def __init__( self, embedding_dim: float = 768, ffn_embedding_dim: float = 3072, num_attention_heads: float = 8, dropout: float = 0.1, attention_dropout: float = 0.1, activation_dropout: float = 0.1, activation_fn: str = "relu", layer_norm_first: bool = False, has_relative_attention_bias: bool = False, num_buckets: int = 0, max_distance: int = 0, rescale_init: bool = False, gru_rel_pos: bool = False, ) -> None: super().__init__() # Initialize parameters self.embedding_dim = embedding_dim self.dropout = dropout self.activation_dropout = activation_dropout # Initialize blocks self.activation_name = activation_fn self.activation_fn = get_activation_fn(activation_fn) self.self_attn = MultiheadAttention( self.embedding_dim, num_attention_heads, dropout=attention_dropout, self_attention=True, has_relative_attention_bias=has_relative_attention_bias, num_buckets=num_buckets, max_distance=max_distance, rescale_init=rescale_init, gru_rel_pos=gru_rel_pos, ) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(self.activation_dropout) self.dropout3 = nn.Dropout(dropout) self.layer_norm_first = layer_norm_first # layer norm associated with the self attention layer self.self_attn_layer_norm = LayerNorm(self.embedding_dim) if self.activation_name == "glu": self.fc1 = GLU_Linear(self.embedding_dim, ffn_embedding_dim, "swish") else: self.fc1 = nn.Linear(self.embedding_dim, ffn_embedding_dim) self.fc2 = nn.Linear(ffn_embedding_dim, self.embedding_dim) # layer norm associated with the position wise feed-forward NN self.final_layer_norm = LayerNorm(self.embedding_dim) def forward( self, x: torch.Tensor, self_attn_mask: torch.Tensor = None, self_attn_padding_mask: torch.Tensor = None, need_weights: bool = False, pos_bias=None, ): """ LayerNorm is applied either before or after the self-attention/ffn modules similar to the original Transformer imlementation. """ residual = x if self.layer_norm_first: x = self.self_attn_layer_norm(x) x, attn, pos_bias = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, need_weights=False, attn_mask=self_attn_mask, position_bias=pos_bias, ) x = self.dropout1(x) x = residual + x residual = x x = self.final_layer_norm(x) if self.activation_name == "glu": x = self.fc1(x) else: x = self.activation_fn(self.fc1(x)) x = self.dropout2(x) x = self.fc2(x) x = self.dropout3(x) x = residual + x else: x, attn, pos_bias = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, need_weights=need_weights, attn_mask=self_attn_mask, position_bias=pos_bias, ) x = self.dropout1(x) x = residual + x x = self.self_attn_layer_norm(x) residual = x if self.activation_name == "glu": x = self.fc1(x) else: x = self.activation_fn(self.fc1(x)) x = self.dropout2(x) x = self.fc2(x) x = self.dropout3(x) x = residual + x x = self.final_layer_norm(x) return x, attn, pos_bias
0
coqui_public_repos/STT-examples/uwp
coqui_public_repos/STT-examples/uwp/STTUWP/App.xaml
<Application x:Class="STTUWP.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:STTUWP"> </Application>
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-nodejs_14x-win-amd64-opt.yml
build: template_file: test-win-opt-base.tyml dependencies: - "win-amd64-cpu-opt" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${system.sox_win} && ${nodejs.win.prep_14} args: tests_cmdline: "${system.homedir.win}/DeepSpeech/ds/taskcluster/tc-node-tests.sh 14.x 16k" metadata: name: "DeepSpeech Windows AMD64 CPU NodeJS 14.x tests" description: "Testing DeepSpeech for Windows/AMD64 on NodeJS v14.x, CPU only, optimized version"
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/linux-amd64-cpu-dbg.yml
build: template_file: linux-opt-base.tyml dependencies: - "swig-linux-amd64" - "node-gyp-cache" - "pyenv-linux-amd64" - "tf_linux-amd64-cpu_gcc9" routes: - "index.project.deepspeech.deepspeech.native_client.${event.head.branchortag}.cpu-dbg" - "index.project.deepspeech.deepspeech.native_client.${event.head.branchortag}.${event.head.sha}.cpu-dbg" - "index.project.deepspeech.deepspeech.native_client.cpu-dbg.${event.head.sha}" tensorflow: ${system.tensorflow_gcc9.linux_amd64_cpu.url} docker_image: "ubuntu:20.04" system_config: > ${deepspeech.packages_bionic.apt} scripts: setup: "taskcluster/tc-true.sh" build: "taskcluster/host-build-dbg.sh" package: "taskcluster/package.sh" nc_asset_name: "native_client.amd64.cpu.linux_dbg.tar.xz" workerType: "${docker.tfBuild}" metadata: name: "DeepSpeech Linux AMD64 CPU Debug" description: "Building DeepSpeech for Linux/AMD64, CPU only, debug version"
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/tc-python_tflite-tests-prod.sh
#!/bin/bash set -xe source $(dirname "$0")/tc-tests-utils.sh extract_python_versions "$1" "pyver" "pyver_pkg" "py_unicode_type" "pyconf" "pyalias" bitrate=$2 set_ldc_sample_filename "${bitrate}" model_source=${DEEPSPEECH_PROD_MODEL//.pb/.tflite} model_name=$(basename "${model_source}") model_name_mmap=$(basename "${model_source}") model_source_mmap=${DEEPSPEECH_PROD_MODEL_MMAP//.pbmm/.tflite} download_data maybe_setup_virtualenv_cross_arm "${pyalias}" "deepspeech" virtualenv_activate "${pyalias}" "deepspeech" pkg_name=$(get_tflite_python_pkg_name) deepspeech_pkg_url=$(get_python_pkg_url "${pyver_pkg}" "${py_unicode_type}" "${pkg_name}") LD_LIBRARY_PATH=${PY37_LDPATH}:$LD_LIBRARY_PATH pip install --verbose --only-binary :all: --upgrade ${deepspeech_pkg_url} | cat which deepspeech deepspeech --version run_prodtflite_inference_tests "${bitrate}" virtualenv_deactivate "${pyalias}" "deepspeech"
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/compress/randmod.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Generates a random FST according to a class-specific transition model. #ifndef FST_EXTENSIONS_COMPRESS_RANDMOD_H_ #define FST_EXTENSIONS_COMPRESS_RANDMOD_H_ #include <vector> #include <fst/compat.h> #include <fst/mutable-fst.h> namespace fst { template <class Arc, class G> class RandMod { public: typedef typename Arc::StateId StateId; typedef typename Arc::Label Label; typedef typename Arc::Weight Weight; // Generates random FST with 'nstates' with 'nclasses' in the probability // generation model, and 'nlabels' in the alphabet. If 'trans' = true, then // a transducer is generated; iff 'generate_' is non-null, the output is // randomly weighted. RandMod(StateId nstates, StateId nclasses, Label nlabels, bool trans, const G *generate) : nstates_(nstates), nclasses_(nclasses), nlabels_(nlabels), trans_(trans), generate_(generate) { for (StateId s = 0; s < nstates; ++s) { classes_.push_back(rand() % nclasses); // NOLINT } } // Generates a random FST according to a class-specific transition model void Generate(StdMutableFst *fst) { StateId start = rand() % nstates_; // NOLINT fst->DeleteStates(); for (StateId s = 0; s < nstates_; ++s) { fst->AddState(); if (s == start) fst->SetStart(start); for (StateId n = 0; n <= nstates_; ++n) { Arc arc; StateId d = n == nstates_ ? kNoStateId : n; if (!RandArc(s, d, &arc)) continue; if (d == kNoStateId) { // A super-final transition? fst->SetFinal(s, arc.weight); } else { fst->AddArc(s, arc); } } } } private: // Generates a transition from s to d. If d == kNoStateId, a superfinal // transition is generated. Returns false if no transition generated. bool RandArc(StateId s, StateId d, Arc *arc) { StateId sclass = classes_[s]; StateId dclass = d != kNoStateId ? classes_[d] : 0; int r = sclass + dclass + 2; if ((rand() % r) != 0) // NOLINT return false; arc->nextstate = d; Label ilabel = kNoLabel; Label olabel = kNoLabel; if (d != kNoStateId) { ilabel = (dclass % nlabels_) + 1; if (trans_) olabel = (sclass % nlabels_) + 1; else olabel = ilabel; } Weight weight = Weight::One(); if (generate_) weight = (*generate_)(); arc->ilabel = ilabel; arc->olabel = olabel; arc->weight = weight; return true; } StateId nstates_; StateId nclasses_; Label nlabels_; bool trans_; const G *generate_; std::vector<StateId> classes_; }; } // namespace fst #endif // FST_EXTENSIONS_COMPRESS_RANDMOD_H_
0
coqui_public_repos/STT-examples/uwp/STTUWP
coqui_public_repos/STT-examples/uwp/STTUWP/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("STTUWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("STTUWP")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/compact/compact16_unweighted-fst.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/fst.h> #include <fst/compact-fst.h> namespace fst { static FstRegisterer<CompactUnweightedFst<StdArc, uint16>> CompactUnweightedFst_StdArc_uint16_registerer; static FstRegisterer<CompactUnweightedFst<LogArc, uint16>> CompactUnweightedFst_LogArc_uint16_registerer; } // namespace fst
0
coqui_public_repos/STT/native_client
coqui_public_repos/STT/native_client/javascript/tsconfig.json
{ "compilerOptions": { "baseUrl": ".", "target": "es6", "module": "commonjs", "moduleResolution": "node", "esModuleInterop": true, "noImplicitAny": true, "noImplicitThis": true, "strictFunctionTypes": true, "strictNullChecks": true, "forceConsistentCasingInFileNames": true, "alwaysStrict": true, "declaration": true, "stripInternal": true }, "files": [ "index.ts", "client.ts", "node-pre-gyp.d.ts" ] }
0
coqui_public_repos/snakepit/src
coqui_public_repos/snakepit/src/routes/jobs.js
const fs = require('fs-extra') const path = require('path') const Tail = require('tail').Tail const Parallel = require('async-parallel') const Sequelize = require('sequelize') const Router = require('express-promise-router') const Pit = require('../models/Pit-model.js') const Job = require('../models/Job-model.js') const config = require('../config.js') const scheduler = require('../scheduler.js') const pitRunner = require('../pitRunner.js') const reservations = require('../reservations.js') const parseClusterRequest = require('../clusterParser.js').parse const log = require('../utils/logger.js') const simplefs = require('../utils/simplefs.js') const clusterEvents = require('../utils/clusterEvents.js') const { getDuration } = require('../utils/dateTime.js') const { ensureSignedIn, ensureUpgrade, targetJob, targetInstance, targetGroup } = require('./mw.js') const jobStates = Job.jobStates var router = module.exports = new Router() router.use(ensureSignedIn) router.post('/', async (req, res) => { let job = req.body let clusterRequest try { clusterRequest = parseClusterRequest(job.clusterRequest) } catch (ex) { res.status(400).send({ message: 'Problem parsing allocation' }) return } if (!(await reservations.canAllocate(clusterRequest, req.user))) { res.status(406).send({ message: 'Cluster cannot fulfill resource request' }) return } if (job.continueJob) { let continueJob = await Job.findByPk(job.continueJob) if (!continueJob) { res.status(404).send({ message: 'The job to continue is not existing' }) return } if (!(await req.user.canAccessJob(continueJob))) { res.status(403).send({ message: 'Continuing provided job not allowed for current user' }) return } } let pit let newJob let archivePath try { let provisioning if (job.origin) { if (job.hash) { provisioning = 'Git commit ' + job.hash + ' from ' + job.origin } else { provisioning = 'Git clone of ' + job.origin } } else if (job.archive) { let basePath = req.user.getDir() archivePath = path.resolve(basePath, job.archive) if (!archivePath.startsWith(basePath)) { res.status(403).send({ message: 'Archive outside user home' }) return } if (!(await fs.pathExists(archivePath))) { res.status(404).send({ message: 'Archive not found' }) return } provisioning = 'Archive (' + (await fs.stat(basePath)).size + ' bytes)' } else { provisioning = 'Script' } if (job.diff) { provisioning += ' with ' + (job.diff + '').split('\n').length + ' LoC diff' } pit = await Pit.create() newJob = await Job.create({ id: pit.id, userId: req.user.id, description: ('' + job.description).substring(0,40), provisioning: provisioning, request: job.clusterRequest, continues: job.continueJob }) if (!job.private) { for(let autoshare of (await req.user.getAutoshares())) { await Job.JobGroup.create({ jobId: newJob.id, groupId: autoshare.groupId }) } } let files = {} files['script.sh'] = (job.script || 'if [ -f .compute ]; then bash .compute; fi') + '\n' if (job.origin) { files['origin'] = job.origin if (job.hash) { files['hash'] = job.hash } } else if (archivePath) { await fs.copy(archivePath, path.join(newJob.getDir(), 'archive.tar.gz')) } if (job.diff) { files['git.patch'] = job.diff + '\n' } let jobDir = Pit.getDir(pit.id) await Parallel.each(Object.keys(files), filename => fs.writeFile(path.join(jobDir, filename), files[filename])) await newJob.setState(jobStates.NEW) res.status(200).send({ id: pit.id }) } catch (ex) { if (newJob) { await newJob.destroy() } if (pit) { await pit.destroy() } res.status(500).send({ message: ex.toString() }) } }) function getJobDescription(job) { return { id: job.id, description: job.description, user: job.userId, resources: job.allocation || job.request, state: job.state, date: job.since, since: getDuration(new Date(), job.since), schedulePosition: job.rank, utilComp: job.state == jobStates.RUNNING ? job.dataValues.curcompute : (job.dataValues.aggcompute / (job.dataValues.samples || 1)), utilMem: job.state == jobStates.RUNNING ? job.dataValues.curmemory : (job.dataValues.aggmemory / (job.dataValues.samples || 1)) } } router.get('/', async (req, res) => { const orderings = { 'date': 'since', 'user': 'user', 'title': 'description', 'state': 'state' } let query = { where: {}, order: [], limit: config.queryLimit } const parseDate = v => { try { return new Date(v) } catch (ex) { return null } } let parsers = { since: v => parseDate(v) ? (query.where.since = { [Sequelize.Op.gte]: parseDate(v) }) : false, till: v => parseDate(v) ? (query.where.since = { [Sequelize.Op.lte]: parseDate(v) }) : false, user: v => query.where.userId = v, title: v => query.where.description = { [Sequelize.Op.like]: v }, asc: v => orderings[v] ? query.order.push([orderings[v], 'ASC']) : false, desc: v => orderings[v] ? query.order.push([orderings[v], 'DESC']) : false, limit: v => !isNaN(parseInt(v)) && (query.limit = Math.min(v, query.limit)), offset: v => !isNaN(parseInt(v)) && (query.offset = v) } for(let param of Object.keys(req.query)) { let parser = parsers[param] if (parser) { if (!parser(req.query[param])) { res.status(400).send({ message: 'Cannot parse query parameter ' + param }) return } } else { res.status(400).send({ message: 'Unknown query parameter ' + param }) return } } query.order.push(['since', 'DESC']) let jobs = await Job.findAll(Job.infoQuery(query)) res.send(jobs.map(job => getJobDescription(job))) }) router.get('/status', async (req, res) => { let query = Job.infoQuery({ where: { state: { [Sequelize.Op.gte]: jobStates.NEW, [Sequelize.Op.lte]: jobStates.STOPPING } } }) let jobs = await Job.findAll(query) let running = jobs .filter(j => j.state >= jobStates.STARTING && j.state <= jobStates.STOPPING) .sort((a,b) => a.id - b.id) let waiting = jobs .filter(j => j.state == jobStates.WAITING) .sort((a,b) => a.rank - b.rank) waiting = waiting.concat(jobs.filter(j => j.state == jobStates.PREPARING)) waiting = waiting.concat(jobs.filter(j => j.state == jobStates.NEW)) let done = await Job.findAll(Job.infoQuery({ where: { state: { [Sequelize.Op.gt]: jobStates.STOPPING } }, order: [['since', 'DESC']], limit: 20 })) res.send({ running: running.map(job => getJobDescription(job)), waiting: waiting.map(job => getJobDescription(job)), done: done .map(job => getJobDescription(job)) }) }) router.get('/:job', async (req, res) => { let query = Job.infoQuery({ where: { id: req.params.job } }) let job = await Job.findOne(query) if (!job) { return Promise.reject({ code: 404, message: 'Job not found' }) } let description = getJobDescription(job) description.allocation = job.allocation description.clusterRequest = job.clusterRequest if (job.continues) { description.continueJob = job.continues } if(await req.user.canAccessJob(job)) { let groups = (await job.getJobgroups()).map(jg => jg.groupId) description.provisioning = job.provisioning description.groups = groups.length > 0 && groups description.stateChanges = (await job.getStates({ order: ['since'] })).map(s => ({ state: s.state, since: s.since, reason: s.reason })) let processes = [] for(let processGroup of await job.getProcessgroups()) { for(let jobProcess of await processGroup.getProcesses()) { processes.push({ groupIndex: processGroup.index, processIndex: jobProcess.index, status: (jobProcess.status === 0 || jobProcess.status > 0) ? jobProcess.status : '?', result: jobProcess.result }) } } if (processes.length > 0) { description.processes = processes } } res.send(description) }) async function canAccess (req, res) { return (await req.user.canAccessJob(req.targetJob)) ? Promise.resolve('next') : Promise.reject({ code: 403, message: 'Forbidden' }) } router.put('/:job/groups/:group', targetJob, canAccess, targetGroup, async (req, res) => { await Job.JobGroup.upsert({ jobId: req.targetJob.id, groupId: req.targetGroup.id }) res.send() }) router.delete('/:job/groups/:group', targetJob, canAccess, targetGroup, async (req, res) => { await Job.JobGroup.destroy({ where: { jobId: req.targetJob.id, groupId: req.targetGroup.id } }) res.send() clusterEvents.emit('restricted') }) router.all('/:job/simplefs/' + simplefs.pattern, targetJob, canAccess, async (req, res) => { let baseDir = Pit.getDir(req.targetJob.id) await simplefs.performCommand(baseDir, req, res) }) router.get('/:job/log', targetJob, canAccess, async (req, res) => { res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type': 'text/plain', 'Cache-Control': 'no-cache' }) req.connection.setTimeout(60 * 60 * 1000) let interval = config.pollInterval let logPath = path.join(Pit.getDir(req.targetJob.id), 'pit.log') if (req.targetJob.state < jobStates.DONE) { let tail let startTail = () => { tail = new Tail(logPath, { fromBeginning: true }) tail.on("line", line => !res.finished && res.write(line + '\n')) tail.on("error", stopTail) res.on('close', stopTail) res.on('end', stopTail) } let stopTail = () => { if (tail) { tail.unwatch() tail = null } res.end() } let poll = () => { if (tail) { req.targetJob.reload().then(() => { if (req.targetJob.state == jobStates.DONE) { stopTail() } else { setTimeout(poll, interval) } }).catch(stopTail) } else { if (fs.existsSync(logPath)) { startTail() } setTimeout(poll, interval) } } poll() } else if (fs.existsSync(logPath)) { let stream = fs.createReadStream(logPath) stream.on('data', chunk => res.write(chunk)) stream.on('end', res.end.bind(res)) } else { res.status(404).send() } }) router.get('/:job/instances/:instance/exec', ensureUpgrade, targetJob, targetInstance, canAccess, async (req, res) => { if (!req.query.context) { throw { code: 400, message: 'No command' } } let context = JSON.parse(req.query.context) let pitSockets = await pitRunner.exec(req.targetJob.id, req.targetInstance, context) if (!pitSockets) { throw { code: 404, message: 'Worker not active' } } res.openSocket(async client => { let stdin = pitSockets['0'] let control = pitSockets.control client.on('message', msg => { if (msg[0] == 0 && control.readyState === control.OPEN) { control.send(msg.slice(1)) } else if (msg[0] == 1 && stdin.readyState === stdin.OPEN) { stdin.send(msg.slice(1)) } }) let sendToClient = (buffer, n) => { if (client.readyState === client.OPEN) { client.send(Buffer.concat([ new Buffer([n]), Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer) ])) } } let sockets if (context.interactive) { sockets = [client, control, stdin] stdin.on('message', msg => sendToClient(msg, 1)) } else { let stdout = pitSockets['1'] let stderr = pitSockets['2'] sockets = [client, control, stdin, stdout, stderr] stdout.on('message', msg => sendToClient(msg, 1)) stderr.on('message', msg => sendToClient(msg, 2)) } control.on('message', msg => sendToClient(msg, 0)) let close = () => sockets.forEach(s => s && s.close()) sockets.forEach(s => s && s.on('close', close)) }) }) router.get('/:job/instances/:instance/forward', ensureUpgrade, targetJob, targetInstance, canAccess, async (req, res) => { let pitSockets = await pitRunner.exec(req.targetJob.id, req.targetInstance, { command: ['forwarder.sh'], interactive: false }) if (!pitSockets) { throw { code: 404, message: 'Worker not active' } } res.openSocket(async client => { let stdin = pitSockets['0'] let stdout = pitSockets['1'] let sockets = [client, stdin, stdout, pitSockets['2'], pitSockets['control']] let connected = true client.on('message', msg => connected && stdin .send(msg)) stdout.on('message', msg => connected && client.send(msg)) let close = () => { connected = false; sockets.forEach(s => s.close()) } sockets.forEach(s => s.on('close', close)) }) }) router.post('/:job/stop', targetJob, canAccess, async (req, res) => { if (req.targetJob.state <= jobStates.STOPPING) { await scheduler.stopJob(req.targetJob, 'Stopped by user ' + req.user.id) res.send() } else { res.status(412).send({ message: 'Only jobs before or in running state can be stopped' }) } }) router.delete('/:job', targetJob, canAccess, async (req, res) => { if (req.targetJob.state >= jobStates.DONE) { await req.targetJob.destroy() res.send() } else { res.status(412).send({ message: 'Only stopped jobs can be deleted' }) } })
0
coqui_public_repos/TTS/TTS/tts/utils
coqui_public_repos/TTS/TTS/tts/utils/monotonic_align/setup.py
# from distutils.core import setup # from Cython.Build import cythonize # import numpy # setup(name='monotonic_align', # ext_modules=cythonize("core.pyx"), # include_dirs=[numpy.get_include()])
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/script/getters.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Getters for converting command-line arguments into the appropriate enums // or bitmasks, with the simplest ones defined as inline. #ifndef FST_SCRIPT_GETTERS_H_ #define FST_SCRIPT_GETTERS_H_ #include <string> #include <fst/compose.h> // For ComposeFilter. #include <fst/determinize.h> // For DeterminizeType. #include <fst/encode.h> // For kEncodeLabels (etc.). #include <fst/epsnormalize.h> // For EpsNormalizeType. #include <fst/project.h> // For ProjectType. #include <fst/push.h> // For kPushWeights (etc.). #include <fst/queue.h> // For QueueType. #include <fst/rational.h> // For ClosureType. #include <fst/script/arcsort.h> // For ArcSortType. #include <fst/script/map.h> // For MapType. #include <fst/script/script-impl.h> // For RandArcSelection. #include <fst/log.h> namespace fst { namespace script { bool GetArcSortType(const string &str, ArcSortType *sort_type); inline ClosureType GetClosureType(bool closure_plus) { return closure_plus ? CLOSURE_PLUS : CLOSURE_STAR; } bool GetComposeFilter(const string &str, ComposeFilter *compose_filter); bool GetDeterminizeType(const string &str, DeterminizeType *det_type); inline uint32_t GetEncodeFlags(bool encode_labels, bool encode_weights) { return (encode_labels ? kEncodeLabels : 0) | (encode_weights ? kEncodeWeights : 0); } inline EpsNormalizeType GetEpsNormalizeType(bool eps_norm_output) { return eps_norm_output ? EPS_NORM_OUTPUT : EPS_NORM_INPUT; } bool GetMapType(const string &str, MapType *map_type); inline ProjectType GetProjectType(bool project_output) { return project_output ? PROJECT_OUTPUT : PROJECT_INPUT; } inline uint32_t GetPushFlags(bool push_weights, bool push_labels, bool remove_total_weight, bool remove_common_affix) { return ((push_weights ? kPushWeights : 0) | (push_labels ? kPushLabels : 0) | (remove_total_weight ? kPushRemoveTotalWeight : 0) | (remove_common_affix ? kPushRemoveCommonAffix : 0)); } bool GetQueueType(const string &str, QueueType *queue_type); bool GetRandArcSelection(const string &str, RandArcSelection *ras); bool GetReplaceLabelType(const string &str, bool epsilon_on_replace, ReplaceLabelType *rlt); inline ReweightType GetReweightType(bool to_final) { return to_final ? REWEIGHT_TO_FINAL : REWEIGHT_TO_INITIAL; } } // namespace script } // namespace fst #endif // FST_SCRIPT_GETTERS_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/bin/fstproject-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Projects a transduction onto its input or output language. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/script/getters.h> #include <fst/script/project.h> DECLARE_bool(project_output); int fstproject_main(int argc, char **argv) { namespace s = fst::script; using fst::script::MutableFstClass; string usage = "Projects a transduction onto its input" " or output language.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true)); if (!fst) return 1; s::Project(fst.get(), s::GetProjectType(FLAGS_project_output)); return !fst->Write(out_name); }
0
coqui_public_repos/STT-models/irish/itml
coqui_public_repos/STT-models/irish/itml/v0.1.1/LICENSE
GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see <https://www.gnu.org/licenses/>.
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/node-package-gpu.yml
build: template_file: node-package-opt-base.tyml dependencies: - "linux-amd64-gpu-opt" - "win-amd64-gpu-opt" system_setup: > ${nodejs.packages_xenial.prep_12} && ${nodejs.packages_xenial.apt_pinning} && apt-get -qq update && apt-get -qq -y install nodejs python-yaml scripts: build: "taskcluster/node-build.sh --cuda" package: "taskcluster/node-package.sh" workerType: "${docker.smallTask}" metadata: name: "DeepSpeech NodeJS GPU package" description: "Packaging DeepSpeech GPU for registry"
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/bin/fstarcsort-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Sorts arcs of an FST. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/log.h> #include <fst/script/arcsort.h> #include <fst/script/getters.h> DECLARE_string(sort_type); int fstarcsort_main(int argc, char **argv) { namespace s = fst::script; using fst::script::MutableFstClass; string usage = "Sorts arcs of an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && (strcmp(argv[1], "-") != 0)) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true)); if (!fst) return 1; s::ArcSortType sort_type; if (!s::GetArcSortType(FLAGS_sort_type, &sort_type)) { LOG(ERROR) << argv[0] << ": Unknown or unsupported sort type: " << FLAGS_sort_type; return 1; } s::ArcSort(fst.get(), sort_type); return !fst->Write(out_name); }
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/bin/fstrelabel-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Relabels input or output space of an FST. #include <cstring> #include <memory> #include <string> #include <vector> #include <fst/flags.h> #include <fst/util.h> #include <fst/script/relabel.h> #include <fst/script/weight-class.h> DECLARE_string(isymbols); DECLARE_string(osymbols); DECLARE_string(relabel_isymbols); DECLARE_string(relabel_osymbols); DECLARE_string(relabel_ipairs); DECLARE_string(relabel_opairs); DECLARE_string(unknown_isymbol); DECLARE_string(unknown_osymbol); DECLARE_bool(allow_negative_labels); int fstrelabel_main(int argc, char **argv) { namespace s = fst::script; using fst::script::MutableFstClass; using fst::SymbolTable; using fst::SymbolTableTextOptions; string usage = "Relabels the input and/or the output labels of the FST.\n\n" " Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; usage += "\n Using SymbolTables flags:\n"; usage += " --relabel_isymbols isyms.map\n"; usage += " --relabel_osymbols osyms.map\n"; usage += "\n Using numeric labels flags:\n"; usage += " --relabel_ipairs ipairs.txt\n"; usage += " --relabel_opairs opairs.txt\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && (strcmp(argv[1], "-") != 0)) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true)); if (!fst) return 1; // Relabel with symbol tables. const SymbolTableTextOptions opts(FLAGS_allow_negative_labels); if (!FLAGS_relabel_isymbols.empty() || !FLAGS_relabel_osymbols.empty()) { bool attach_new_isymbols = (fst->InputSymbols() != nullptr); std::unique_ptr<const SymbolTable> old_isymbols( FLAGS_isymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_isymbols, opts)); const std::unique_ptr<const SymbolTable> relabel_isymbols( FLAGS_relabel_isymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_relabel_isymbols, opts)); bool attach_new_osymbols = (fst->OutputSymbols() != nullptr); std::unique_ptr<const SymbolTable> old_osymbols( FLAGS_osymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_osymbols, opts)); const std::unique_ptr<const SymbolTable> relabel_osymbols( FLAGS_relabel_osymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_relabel_osymbols, opts)); s::Relabel(fst.get(), old_isymbols ? old_isymbols.get() : fst->InputSymbols(), relabel_isymbols.get(), FLAGS_unknown_isymbol, attach_new_isymbols, old_osymbols ? old_osymbols.get() : fst->OutputSymbols(), relabel_osymbols.get(), FLAGS_unknown_osymbol, attach_new_osymbols); } else { // Reads in relabeling pairs. std::vector<s::LabelPair> ipairs; std::vector<s::LabelPair> opairs; if (!FLAGS_relabel_ipairs.empty()) { if (!fst::ReadLabelPairs(FLAGS_relabel_ipairs, &ipairs, FLAGS_allow_negative_labels)) return 1; } if (!FLAGS_relabel_opairs.empty()) { if (!fst::ReadLabelPairs(FLAGS_relabel_opairs, &opairs, FLAGS_allow_negative_labels)) return 1; } s::Relabel(fst.get(), ipairs, opairs); } return !fst->Write(out_name); }
0
coqui_public_repos/TTS/TTS
coqui_public_repos/TTS/TTS/utils/capacitron_optimizer.py
from typing import Generator from trainer.trainer_utils import get_optimizer class CapacitronOptimizer: """Double optimizer class for the Capacitron model.""" def __init__(self, config: dict, model_params: Generator) -> None: self.primary_params, self.secondary_params = self.split_model_parameters(model_params) optimizer_names = list(config.optimizer_params.keys()) optimizer_parameters = list(config.optimizer_params.values()) self.primary_optimizer = get_optimizer( optimizer_names[0], optimizer_parameters[0], config.lr, parameters=self.primary_params, ) self.secondary_optimizer = get_optimizer( optimizer_names[1], self.extract_optimizer_parameters(optimizer_parameters[1]), optimizer_parameters[1]["lr"], parameters=self.secondary_params, ) self.param_groups = self.primary_optimizer.param_groups def first_step(self): self.secondary_optimizer.step() self.secondary_optimizer.zero_grad() self.primary_optimizer.zero_grad() def step(self): # Update param groups to display the correct learning rate self.param_groups = self.primary_optimizer.param_groups self.primary_optimizer.step() def zero_grad(self, set_to_none=False): self.primary_optimizer.zero_grad(set_to_none) self.secondary_optimizer.zero_grad(set_to_none) def load_state_dict(self, state_dict): self.primary_optimizer.load_state_dict(state_dict[0]) self.secondary_optimizer.load_state_dict(state_dict[1]) def state_dict(self): return [self.primary_optimizer.state_dict(), self.secondary_optimizer.state_dict()] @staticmethod def split_model_parameters(model_params: Generator) -> list: primary_params = [] secondary_params = [] for name, param in model_params: if param.requires_grad: if name == "capacitron_vae_layer.beta": secondary_params.append(param) else: primary_params.append(param) return [iter(primary_params), iter(secondary_params)] @staticmethod def extract_optimizer_parameters(params: dict) -> dict: """Extract parameters that are not the learning rate""" return {k: v for k, v in params.items() if k != "lr"}
0
coqui_public_repos/STT-models/breton/itml
coqui_public_repos/STT-models/breton/itml/v0.1.0/MODEL_CARD.md
# Model card for Breton STT Jump to section: - [Model details](#model-details) - [Intended use](#intended-use) - [Performance Factors](#performance-factors) - [Metrics](#metrics) - [Training data](#training-data) - [Evaluation data](#evaluation-data) - [Ethical considerations](#ethical-considerations) - [Caveats and recommendations](#caveats-and-recommendations) ## Model details - Person or organization developing model: Originally trained by [Francis Tyers](https://scholar.google.fr/citations?user=o5HSM6cAAAAJ) and the [Inclusive Technology for Marginalised Languages](https://itml.cl.indiana.edu/) group. - Model language: Breton / Brezhoneg / `br` - Model date: April 9, 2021 - Model type: `Speech-to-Text` - Model version: `v0.1.0` - Compatible with 🐸 STT version: `v0.9.3` - License: AGPL - Citation details: `@techreport{breton-stt, author = {Tyers,Francis}, title = {Breton STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2021}, month = {April}, number = {STT-CV6.1-BR-0.1} }` - Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/). ## Intended use Speech-to-Text for the [Breton Language](https://en.wikipedia.org/wiki/Breton_language) on 16kHz, mono-channel audio. ## Performance Factors Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). ## Metrics STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk. #### Transcription Accuracy The following Word Error Rates and Character Error Rates are reported on [omnilingo](https://tepozcatl.omnilingo.cc/cv/). |Test Corpus|WER|CER| |-----------|---|---| |Common Voice|94.9\%|41.6\%| #### Real-Time Factor Real-Time Factor (RTF) is defined as `processing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF. Recorded average RTF on laptop CPU: `` #### Model Size `model.pbmm`: 181M `model.tflite`: 46M ### Approaches to uncertainty and variability Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio. ## Training data This model was trained on Common Voice 6.1 train. ## Evaluation data The Model was evaluated on Common Voice 6.1 test. ## Ethical considerations Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use. ### Demographic Bias You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue. ### Surveillance Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech. ## Caveats and recommendations Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/script/determinize.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_DETERMINIZE_H_ #define FST_SCRIPT_DETERMINIZE_H_ #include <tuple> #include <fst/determinize.h> #include <fst/script/fst-class.h> #include <fst/script/weight-class.h> namespace fst { namespace script { struct DeterminizeOptions { const float delta; const WeightClass &weight_threshold; const int64 state_threshold; const int64 subsequential_label; const DeterminizeType det_type; const bool increment_subsequential_label; DeterminizeOptions(float delta, const WeightClass &weight_threshold, int64 state_threshold = kNoStateId, int64 subsequential_label = 0, DeterminizeType det_type = DETERMINIZE_FUNCTIONAL, bool increment_subsequential_label = false) : delta(delta), weight_threshold(weight_threshold), state_threshold(state_threshold), subsequential_label(subsequential_label), det_type(det_type), increment_subsequential_label(increment_subsequential_label) {} }; using DeterminizeArgs = std::tuple<const FstClass &, MutableFstClass *, const DeterminizeOptions &>; template <class Arc> void Determinize(DeterminizeArgs *args) { using Weight = typename Arc::Weight; const Fst<Arc> &ifst = *(std::get<0>(*args).GetFst<Arc>()); MutableFst<Arc> *ofst = std::get<1>(*args)->GetMutableFst<Arc>(); const auto &opts = std::get<2>(*args); const auto weight_threshold = *(opts.weight_threshold.GetWeight<Weight>()); const fst::DeterminizeOptions<Arc> detargs(opts.delta, weight_threshold, opts.state_threshold, opts.subsequential_label, opts.det_type, opts.increment_subsequential_label); Determinize(ifst, ofst, detargs); } void Determinize(const FstClass &ifst, MutableFstClass *ofst, const DeterminizeOptions &opts); } // namespace script } // namespace fst #endif // FST_SCRIPT_DETERMINIZE_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/pdt/paren.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Common classes for PDT parentheses. #ifndef FST_EXTENSIONS_PDT_PAREN_H_ #define FST_EXTENSIONS_PDT_PAREN_H_ #include <algorithm> #include <set> #include <unordered_map> #include <unordered_set> #include <fst/log.h> #include <fst/extensions/pdt/collection.h> #include <fst/extensions/pdt/pdt.h> #include <fst/dfs-visit.h> #include <fst/fst.h> namespace fst { namespace internal { // ParenState: Pair of an open (close) parenthesis and its destination (source) // state. template <class Arc> struct ParenState { using Label = typename Arc::Label; using StateId = typename Arc::StateId; Label paren_id; // ID of open (close) paren. StateId state_id; // Destination (source) state of open (close) paren. explicit ParenState(Label paren_id = kNoLabel, StateId state_id = kNoStateId) : paren_id(paren_id), state_id(state_id) {} bool operator==(const ParenState<Arc> &other) const { if (&other == this) return true; return other.paren_id == paren_id && other.state_id == state_id; } bool operator!=(const ParenState<Arc> &other) const { return !(other == *this); } struct Hash { size_t operator()(const ParenState<Arc> &pstate) const { static constexpr auto prime = 7853; return pstate.paren_id + pstate.state_id * prime; } }; }; // Creates an FST-style const iterator from an STL-style map. template <class Map> class MapIterator { public: using StlIterator = typename Map::const_iterator; using ValueType = typename Map::mapped_type; MapIterator(const Map &map, StlIterator it) : begin_(it), end_(map.end()), it_(it) {} bool Done() const { return it_ == end_ || it_->first != begin_->first; } ValueType Value() const { return it_->second; } void Next() { ++it_; } void Reset() { it_ = begin_; } private: const StlIterator begin_; const StlIterator end_; StlIterator it_; }; // PdtParenReachable: Provides various parenthesis reachability information. template <class Arc> class PdtParenReachable { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using State = ParenState<Arc>; using StateHash = typename State::Hash; // Maps from state ID to reachable paren IDs from (to) that state. using ParenMultimap = std::unordered_multimap<StateId, Label>; // Maps from paren ID and state ID to reachable state set ID. using StateSetMap = std::unordered_map<State, ssize_t, StateHash>; // Maps from paren ID and state ID to arcs exiting that state with that // Label. using ParenArcMultimap = std::unordered_map<State, Arc, StateHash>; using ParenIterator = MapIterator<ParenMultimap>; using ParenArcIterator = MapIterator<ParenArcMultimap>; using SetIterator = typename Collection<ssize_t, StateId>::SetIterator; // Computes close (open) parenthesis reachability information for a PDT with // bounded stack. PdtParenReachable(const Fst<Arc> &fst, const std::vector<std::pair<Label, Label>> &parens, bool close) : fst_(fst), parens_(parens), close_(close), error_(false) { paren_map_.reserve(2 * parens.size()); for (size_t i = 0; i < parens.size(); ++i) { const auto &pair = parens[i]; paren_map_[pair.first] = i; paren_map_[pair.second] = i; } if (close_) { const auto start = fst.Start(); if (start == kNoStateId) return; if (!DFSearch(start)) { FSTERROR() << "PdtReachable: Underlying cyclicity not supported"; error_ = true; } } else { FSTERROR() << "PdtParenReachable: Open paren info not implemented"; error_ = true; } } bool Error() const { return error_; } // Given a state ID, returns an iterator over paren IDs for close (open) // parens reachable from that state along balanced paths. ParenIterator FindParens(StateId s) const { return ParenIterator(paren_multimap_, paren_multimap_.find(s)); } // Given a paren ID and a state ID s, returns an iterator over states that can // be reached along balanced paths from (to) s that have have close (open) // parentheses matching the paren ID exiting (entering) those states. SetIterator FindStates(Label paren_id, StateId s) const { const State paren_state(paren_id, s); const auto it = set_map_.find(paren_state); if (it == set_map_.end()) { return state_sets_.FindSet(-1); } else { return state_sets_.FindSet(it->second); } } // Given a paren ID and a state ID s, return an iterator over arcs that exit // (enter) s and are labeled with a close (open) parenthesis matching the // paren ID. ParenArcIterator FindParenArcs(Label paren_id, StateId s) const { const State paren_state(paren_id, s); return ParenArcIterator(paren_arc_multimap_, paren_arc_multimap_.find(paren_state)); } private: // Returns false when cycle detected during DFS gathering paren and state set // information. bool DFSearch(StateId s); // Unions state sets together gathered by the DFS. void ComputeStateSet(StateId s); // Gathers state set(s) from state. void UpdateStateSet(StateId nextstate, std::set<Label> *paren_set, std::vector<std::set<StateId>> *state_sets) const; const Fst<Arc> &fst_; // Paren IDs to labels. const std::vector<std::pair<Label, Label>> &parens_; // Close/open paren info? const bool close_; // Labels to paren IDs. std::unordered_map<Label, Label> paren_map_; // Paren reachability. ParenMultimap paren_multimap_; // Paren arcs. ParenArcMultimap paren_arc_multimap_; // DFS states. std::vector<uint8> state_color_; // Reachable states to IDs. mutable Collection<ssize_t, StateId> state_sets_; // IDs to reachable states. StateSetMap set_map_; bool error_; PdtParenReachable(const PdtParenReachable &) = delete; PdtParenReachable &operator=(const PdtParenReachable &) = delete; }; // Gathers paren and state set information. template <class Arc> bool PdtParenReachable<Arc>::DFSearch(StateId s) { static constexpr uint8 kWhiteState = 0x01; // Undiscovered. static constexpr uint8 kGreyState = 0x02; // Discovered & unfinished. static constexpr uint8 kBlackState = 0x04; // Finished. if (s >= state_color_.size()) state_color_.resize(s + 1, kWhiteState); if (state_color_[s] == kBlackState) return true; if (state_color_[s] == kGreyState) return false; state_color_[s] = kGreyState; for (ArcIterator<Fst<Arc>> aiter(fst_, s); !aiter.Done(); aiter.Next()) { const auto &arc = aiter.Value(); const auto it = paren_map_.find(arc.ilabel); if (it != paren_map_.end()) { // Paren? const auto paren_id = it->second; if (arc.ilabel == parens_[paren_id].first) { // Open paren? if (!DFSearch(arc.nextstate)) return false; for (auto set_iter = FindStates(paren_id, arc.nextstate); !set_iter.Done(); set_iter.Next()) { for (auto paren_arc_iter = FindParenArcs(paren_id, set_iter.Element()); !paren_arc_iter.Done(); paren_arc_iter.Next()) { const auto &cparc = paren_arc_iter.Value(); if (!DFSearch(cparc.nextstate)) return false; } } } } else if (!DFSearch(arc.nextstate)) { // Non-paren. return false; } } ComputeStateSet(s); state_color_[s] = kBlackState; return true; } // Unions state sets. template <class Arc> void PdtParenReachable<Arc>::ComputeStateSet(StateId s) { std::set<Label> paren_set; std::vector<std::set<StateId>> state_sets(parens_.size()); for (ArcIterator<Fst<Arc>> aiter(fst_, s); !aiter.Done(); aiter.Next()) { const auto &arc = aiter.Value(); const auto it = paren_map_.find(arc.ilabel); if (it != paren_map_.end()) { // Paren? const auto paren_id = it->second; if (arc.ilabel == parens_[paren_id].first) { // Open paren? for (auto set_iter = FindStates(paren_id, arc.nextstate); !set_iter.Done(); set_iter.Next()) { for (auto paren_arc_iter = FindParenArcs(paren_id, set_iter.Element()); !paren_arc_iter.Done(); paren_arc_iter.Next()) { const auto &cparc = paren_arc_iter.Value(); UpdateStateSet(cparc.nextstate, &paren_set, &state_sets); } } } else { // Close paren. paren_set.insert(paren_id); state_sets[paren_id].insert(s); const State paren_state(paren_id, s); paren_arc_multimap_.insert(std::make_pair(paren_state, arc)); } } else { // Non-paren. UpdateStateSet(arc.nextstate, &paren_set, &state_sets); } } std::vector<StateId> state_set; for (auto paren_iter = paren_set.begin(); paren_iter != paren_set.end(); ++paren_iter) { state_set.clear(); const auto paren_id = *paren_iter; paren_multimap_.insert(std::make_pair(s, paren_id)); for (auto state_iter = state_sets[paren_id].begin(); state_iter != state_sets[paren_id].end(); ++state_iter) { state_set.push_back(*state_iter); } const State paren_state(paren_id, s); set_map_[paren_state] = state_sets_.FindId(state_set); } } // Gathers state sets. template <class Arc> void PdtParenReachable<Arc>::UpdateStateSet( StateId nextstate, std::set<Label> *paren_set, std::vector<std::set<StateId>> *state_sets) const { for (auto paren_iter = FindParens(nextstate); !paren_iter.Done(); paren_iter.Next()) { const auto paren_id = paren_iter.Value(); paren_set->insert(paren_id); for (auto set_iter = FindStates(paren_id, nextstate); !set_iter.Done(); set_iter.Next()) { (*state_sets)[paren_id].insert(set_iter.Element()); } } } // Stores balancing parenthesis data for a PDT. Unlike PdtParenReachable above // this allows on-the-fly construction (e.g., in PdtShortestPath). template <class Arc> class PdtBalanceData { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using State = ParenState<Arc>; using StateHash = typename State::Hash; // Set for open parens. using OpenParenSet = std::unordered_set<State, StateHash>; // Maps from open paren destination state to parenthesis ID. using OpenParenMap = std::unordered_multimap<StateId, Label>; // Maps from open paren state to source states of matching close parens using CloseParenMap = std::unordered_multimap<State, StateId, StateHash>; // Maps from open paren state to close source set ID. using CloseSourceMap = std::unordered_map<State, ssize_t, StateHash>; using SetIterator = typename Collection<ssize_t, StateId>::SetIterator; PdtBalanceData() {} void Clear() { open_paren_map_.clear(); close_paren_map_.clear(); } // Adds an open parenthesis with destination state open_dest. void OpenInsert(Label paren_id, StateId open_dest) { const State key(paren_id, open_dest); if (!open_paren_set_.count(key)) { open_paren_set_.insert(key); open_paren_map_.emplace(open_dest, paren_id); } } // Adds a matching closing parenthesis with source state close_source // balancing an open_parenthesis with destination state open_dest if // OpenInsert() previously called. void CloseInsert(Label paren_id, StateId open_dest, StateId close_source) { const State key(paren_id, open_dest); if (open_paren_set_.count(key)) { close_paren_map_.emplace(key, close_source); } } // Finds close paren source states matching an open parenthesis. The following // methods are then used to iterate through those matching states. Should be // called only after FinishInsert(open_dest). SetIterator Find(Label paren_id, StateId open_dest) { const State key(paren_id, open_dest); const auto it = close_source_map_.find(key); if (it == close_source_map_.end()) { return close_source_sets_.FindSet(-1); } else { return close_source_sets_.FindSet(it->second); } } // Called when all open and close parenthesis insertions (w.r.t. open // parentheses entering state open_dest) are finished. Must be called before // Find(open_dest). void FinishInsert(StateId open_dest) { std::vector<StateId> close_sources; for (auto oit = open_paren_map_.find(open_dest); oit != open_paren_map_.end() && oit->first == open_dest;) { const auto paren_id = oit->second; close_sources.clear(); const State key(paren_id, open_dest); open_paren_set_.erase(open_paren_set_.find(key)); for (auto cit = close_paren_map_.find(key); cit != close_paren_map_.end() && cit->first == key;) { close_sources.push_back(cit->second); close_paren_map_.erase(cit++); } std::sort(close_sources.begin(), close_sources.end()); auto unique_end = std::unique(close_sources.begin(), close_sources.end()); close_sources.resize(unique_end - close_sources.begin()); if (!close_sources.empty()) { close_source_map_[key] = close_source_sets_.FindId(close_sources); } open_paren_map_.erase(oit++); } } // Returns a new balance data object representing the reversed balance // information. PdtBalanceData<Arc> *Reverse(StateId num_states, StateId num_split, StateId state_id_shift) const; private: // Open paren at destintation state? OpenParenSet open_paren_set_; // Open parens per state. OpenParenMap open_paren_map_; // Current open destination state. State open_dest_; // Current open paren/state. typename OpenParenMap::const_iterator open_iter_; // Close states to (open paren, state). CloseParenMap close_paren_map_; // (Paren, state) to set ID. CloseSourceMap close_source_map_; mutable Collection<ssize_t, StateId> close_source_sets_; }; // Return a new balance data object representing the reversed balance // information. template <class Arc> PdtBalanceData<Arc> *PdtBalanceData<Arc>::Reverse( StateId num_states, StateId num_split, StateId state_id_shift) const { auto *bd = new PdtBalanceData<Arc>; std::unordered_set<StateId> close_sources; const auto split_size = num_states / num_split; for (StateId i = 0; i < num_states; i += split_size) { close_sources.clear(); for (auto it = close_source_map_.begin(); it != close_source_map_.end(); ++it) { const auto &okey = it->first; const auto open_dest = okey.state_id; const auto paren_id = okey.paren_id; for (auto set_iter = close_source_sets_.FindSet(it->second); !set_iter.Done(); set_iter.Next()) { const auto close_source = set_iter.Element(); if ((close_source < i) || (close_source >= i + split_size)) continue; close_sources.insert(close_source + state_id_shift); bd->OpenInsert(paren_id, close_source + state_id_shift); bd->CloseInsert(paren_id, close_source + state_id_shift, open_dest + state_id_shift); } } for (auto it = close_sources.begin(); it != close_sources.end(); ++it) { bd->FinishInsert(*it); } } return bd; } } // namespace internal } // namespace fst #endif // FST_EXTENSIONS_PDT_PAREN_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstcompile.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/flags.h> DEFINE_bool(acceptor, false, "Input in acceptor format"); DEFINE_string(arc_type, "standard", "Output arc type"); DEFINE_string(fst_type, "vector", "Output FST type"); DEFINE_string(isymbols, "", "Input label symbol table"); DEFINE_string(osymbols, "", "Output label symbol table"); DEFINE_string(ssymbols, "", "State label symbol table"); DEFINE_bool(keep_isymbols, false, "Store input label symbol table with FST"); DEFINE_bool(keep_osymbols, false, "Store output label symbol table with FST"); DEFINE_bool(keep_state_numbering, false, "Do not renumber input states"); DEFINE_bool(allow_negative_labels, false, "Allow negative labels (not recommended; may cause conflicts)"); int fstcompile_main(int argc, char **argv); int main(int argc, char **argv) { return fstcompile_main(argc, argv); }
0
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson/reader.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef CEREAL_RAPIDJSON_READER_H_ #define CEREAL_RAPIDJSON_READER_H_ /*! \file reader.h */ #include "allocators.h" #include "stream.h" #include "encodedstream.h" #include "internal/meta.h" #include "internal/stack.h" #include "internal/strtod.h" #include <limits> #if defined(CEREAL_RAPIDJSON_SIMD) && defined(_MSC_VER) #include <intrin.h> #pragma intrinsic(_BitScanForward) #endif #ifdef CEREAL_RAPIDJSON_SSE42 #include <nmmintrin.h> #elif defined(CEREAL_RAPIDJSON_SSE2) #include <emmintrin.h> #elif defined(CEREAL_RAPIDJSON_NEON) #include <arm_neon.h> #endif #ifdef __clang__ CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_OFF(old-style-cast) CEREAL_RAPIDJSON_DIAG_OFF(padded) CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) #elif defined(_MSC_VER) CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code #endif #ifdef __GNUC__ CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_OFF(effc++) #endif //!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN #define CEREAL_RAPIDJSON_NOTHING /* deliberately empty */ #ifndef CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN #define CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \ CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN \ if (CEREAL_RAPIDJSON_UNLIKELY(HasParseError())) { return value; } \ CEREAL_RAPIDJSON_MULTILINEMACRO_END #endif #define CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \ CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(CEREAL_RAPIDJSON_NOTHING) //!@endcond /*! \def CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN \ingroup CEREAL_RAPIDJSON_ERRORS \brief Macro to indicate a parse error. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error \param offset position of the error in JSON input (\c size_t) This macros can be used as a customization point for the internal error handling mechanism of RapidJSON. A common usage model is to throw an exception instead of requiring the caller to explicitly check the \ref rapidjson::GenericReader::Parse's return value: \code #define CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \ throw ParseException(parseErrorCode, #parseErrorCode, offset) #include <stdexcept> // std::runtime_error #include "rapidjson/error/error.h" // rapidjson::ParseResult struct ParseException : std::runtime_error, rapidjson::ParseResult { ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset) : std::runtime_error(msg), ParseResult(code, offset) {} }; #include "rapidjson/reader.h" \endcode \see CEREAL_RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse */ #ifndef CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN #define CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \ CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN \ CEREAL_RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \ SetParseError(parseErrorCode, offset); \ CEREAL_RAPIDJSON_MULTILINEMACRO_END #endif /*! \def CEREAL_RAPIDJSON_PARSE_ERROR \ingroup CEREAL_RAPIDJSON_ERRORS \brief (Internal) macro to indicate and handle a parse error. \param parseErrorCode \ref rapidjson::ParseErrorCode of the error \param offset position of the error in JSON input (\c size_t) Invokes CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing. \see CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN \hideinitializer */ #ifndef CEREAL_RAPIDJSON_PARSE_ERROR #define CEREAL_RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \ CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN \ CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \ CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \ CEREAL_RAPIDJSON_MULTILINEMACRO_END #endif #include "error/error.h" // ParseErrorCode, ParseResult CEREAL_RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // ParseFlag /*! \def CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS \ingroup CEREAL_RAPIDJSON_CONFIG \brief User-defined kParseDefaultFlags definition. User can define this as any \c ParseFlag combinations. */ #ifndef CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS #define CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags #endif //! Combination of parseFlags /*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream */ enum ParseFlag { kParseNoFlags = 0, //!< No flags are set. kParseInsituFlag = 1, //!< In-situ(destructive) parsing. kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings. kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing. kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error. kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower). kParseCommentsFlag = 32, //!< Allow one-line (//) and multi-line (/**/) comments. kParseNumbersAsStringsFlag = 64, //!< Parse all numbers (ints/doubles) as strings. kParseTrailingCommasFlag = 128, //!< Allow trailing commas at the end of objects and arrays. kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles. kParseDefaultFlags = CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS }; /////////////////////////////////////////////////////////////////////////////// // Handler /*! \class rapidjson::Handler \brief Concept for receiving events from GenericReader upon parsing. The functions return true if no error occurs. If they return false, the event publisher should terminate the process. \code concept Handler { typename Ch; bool Null(); bool Bool(bool b); bool Int(int i); bool Uint(unsigned i); bool Int64(int64_t i); bool Uint64(uint64_t i); bool Double(double d); /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) bool RawNumber(const Ch* str, SizeType length, bool copy); bool String(const Ch* str, SizeType length, bool copy); bool StartObject(); bool Key(const Ch* str, SizeType length, bool copy); bool EndObject(SizeType memberCount); bool StartArray(); bool EndArray(SizeType elementCount); }; \endcode */ /////////////////////////////////////////////////////////////////////////////// // BaseReaderHandler //! Default implementation of Handler. /*! This can be used as base class of any reader handler. \note implements Handler concept */ template<typename Encoding = UTF8<>, typename Derived = void> struct BaseReaderHandler { typedef typename Encoding::Ch Ch; typedef typename internal::SelectIf<internal::IsSame<Derived, void>, BaseReaderHandler, Derived>::Type Override; bool Default() { return true; } bool Null() { return static_cast<Override&>(*this).Default(); } bool Bool(bool) { return static_cast<Override&>(*this).Default(); } bool Int(int) { return static_cast<Override&>(*this).Default(); } bool Uint(unsigned) { return static_cast<Override&>(*this).Default(); } bool Int64(int64_t) { return static_cast<Override&>(*this).Default(); } bool Uint64(uint64_t) { return static_cast<Override&>(*this).Default(); } bool Double(double) { return static_cast<Override&>(*this).Default(); } /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) bool RawNumber(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); } bool String(const Ch*, SizeType, bool) { return static_cast<Override&>(*this).Default(); } bool StartObject() { return static_cast<Override&>(*this).Default(); } bool Key(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); } bool EndObject(SizeType) { return static_cast<Override&>(*this).Default(); } bool StartArray() { return static_cast<Override&>(*this).Default(); } bool EndArray(SizeType) { return static_cast<Override&>(*this).Default(); } }; /////////////////////////////////////////////////////////////////////////////// // StreamLocalCopy namespace internal { template<typename Stream, int = StreamTraits<Stream>::copyOptimization> class StreamLocalCopy; //! Do copy optimization. template<typename Stream> class StreamLocalCopy<Stream, 1> { public: StreamLocalCopy(Stream& original) : s(original), original_(original) {} ~StreamLocalCopy() { original_ = s; } Stream s; private: StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; Stream& original_; }; //! Keep reference. template<typename Stream> class StreamLocalCopy<Stream, 0> { public: StreamLocalCopy(Stream& original) : s(original) {} Stream& s; private: StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; }; } // namespace internal /////////////////////////////////////////////////////////////////////////////// // SkipWhitespace //! Skip the JSON white spaces in a stream. /*! \param is A input stream for skipping white spaces. \note This function has SSE2/SSE4.2 specialization. */ template<typename InputStream> void SkipWhitespace(InputStream& is) { internal::StreamLocalCopy<InputStream> copy(is); InputStream& s(copy.s); typename InputStream::Ch c; while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t') s.Take(); } inline const char* SkipWhitespace(const char* p, const char* end) { while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; return p; } #ifdef CEREAL_RAPIDJSON_SSE42 //! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once. inline const char *SkipWhitespace_SIMD(const char* p) { // Fast return for single non-whitespace if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // 16-byte align to the next boundary const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // The rest of string using SIMD static const char whitespace[16] = " \n\r\t"; const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); if (r != 16) // some of characters is non-whitespace return p + r; } } inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { // Fast return for single non-whitespace if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; else return p; // The middle of string using SIMD static const char whitespace[16] = " \n\r\t"; const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0])); for (; p <= end - 16; p += 16) { const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p)); const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); if (r != 16) // some of characters is non-whitespace return p + r; } return SkipWhitespace(p, end); } #elif defined(CEREAL_RAPIDJSON_SSE2) //! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once. inline const char *SkipWhitespace_SIMD(const char* p) { // Fast return for single non-whitespace if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // 16-byte align to the next boundary const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // The rest of string #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; #undef C16 const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0])); const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0])); const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0])); const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); __m128i x = _mm_cmpeq_epi8(s, w0); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x)); if (r != 0) { // some of characters may be non-whitespace #ifdef _MSC_VER // Find the index of first non-whitespace unsigned long offset; _BitScanForward(&offset, r); return p + offset; #else return p + __builtin_ffs(r) - 1; #endif } } } inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { // Fast return for single non-whitespace if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; else return p; // The rest of string #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; #undef C16 const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0])); const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0])); const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0])); const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0])); for (; p <= end - 16; p += 16) { const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p)); __m128i x = _mm_cmpeq_epi8(s, w0); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x)); if (r != 0) { // some of characters may be non-whitespace #ifdef _MSC_VER // Find the index of first non-whitespace unsigned long offset; _BitScanForward(&offset, r); return p + offset; #else return p + __builtin_ffs(r) - 1; #endif } } return SkipWhitespace(p, end); } #elif defined(CEREAL_RAPIDJSON_NEON) //! Skip whitespace with ARM Neon instructions, testing 16 8-byte characters at once. inline const char *SkipWhitespace_SIMD(const char* p) { // Fast return for single non-whitespace if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; // 16-byte align to the next boundary const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') ++p; else return p; const uint8x16_t w0 = vmovq_n_u8(' '); const uint8x16_t w1 = vmovq_n_u8('\n'); const uint8x16_t w2 = vmovq_n_u8('\r'); const uint8x16_t w3 = vmovq_n_u8('\t'); for (;; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, w0); x = vorrq_u8(x, vceqq_u8(s, w1)); x = vorrq_u8(x, vceqq_u8(s, w2)); x = vorrq_u8(x, vceqq_u8(s, w3)); x = vmvnq_u8(x); // Negate x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract if (low == 0) { if (high != 0) { int lz =__builtin_clzll(high);; return p + 8 + (lz >> 3); } } else { int lz = __builtin_clzll(low);; return p + (lz >> 3); } } } inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { // Fast return for single non-whitespace if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) ++p; else return p; const uint8x16_t w0 = vmovq_n_u8(' '); const uint8x16_t w1 = vmovq_n_u8('\n'); const uint8x16_t w2 = vmovq_n_u8('\r'); const uint8x16_t w3 = vmovq_n_u8('\t'); for (; p <= end - 16; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, w0); x = vorrq_u8(x, vceqq_u8(s, w1)); x = vorrq_u8(x, vceqq_u8(s, w2)); x = vorrq_u8(x, vceqq_u8(s, w3)); x = vmvnq_u8(x); // Negate x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract if (low == 0) { if (high != 0) { int lz = __builtin_clzll(high); return p + 8 + (lz >> 3); } } else { int lz = __builtin_clzll(low); return p + (lz >> 3); } } return SkipWhitespace(p, end); } #endif // CEREAL_RAPIDJSON_NEON #ifdef CEREAL_RAPIDJSON_SIMD //! Template function specialization for InsituStringStream template<> inline void SkipWhitespace(InsituStringStream& is) { is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_)); } //! Template function specialization for StringStream template<> inline void SkipWhitespace(StringStream& is) { is.src_ = SkipWhitespace_SIMD(is.src_); } template<> inline void SkipWhitespace(EncodedInputStream<UTF8<>, MemoryStream>& is) { is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_); } #endif // CEREAL_RAPIDJSON_SIMD /////////////////////////////////////////////////////////////////////////////// // GenericReader //! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator. /*! GenericReader parses JSON text from a stream, and send events synchronously to an object implementing Handler concept. It needs to allocate a stack for storing a single decoded string during non-destructive parsing. For in-situ parsing, the decoded string is directly written to the source text string, no temporary buffer is required. A GenericReader object can be reused for parsing multiple JSON text. \tparam SourceEncoding Encoding of the input stream. \tparam TargetEncoding Encoding of the parse output. \tparam StackAllocator Allocator type for stack. */ template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator> class GenericReader { public: typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type //! Constructor. /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing) \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing) */ GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_(), state_(IterativeParsingStartState) {} //! Parse JSON text. /*! \tparam parseFlags Combination of \ref ParseFlag. \tparam InputStream Type of input stream, implementing Stream concept. \tparam Handler Type of handler, implementing Handler concept. \param is Input stream to be parsed. \param handler The handler to receive events. \return Whether the parsing is successful. */ template <unsigned parseFlags, typename InputStream, typename Handler> ParseResult Parse(InputStream& is, Handler& handler) { if (parseFlags & kParseIterativeFlag) return IterativeParse<parseFlags>(is, handler); parseResult_.Clear(); ClearStackOnExit scope(*this); SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() == '\0')) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell()); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); } else { ParseValue<parseFlags>(is, handler); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); if (!(parseFlags & kParseStopWhenDoneFlag)) { SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() != '\0')) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell()); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); } } } return parseResult_; } //! Parse JSON text (with \ref kParseDefaultFlags) /*! \tparam InputStream Type of input stream, implementing Stream concept \tparam Handler Type of handler, implementing Handler concept. \param is Input stream to be parsed. \param handler The handler to receive events. \return Whether the parsing is successful. */ template <typename InputStream, typename Handler> ParseResult Parse(InputStream& is, Handler& handler) { return Parse<kParseDefaultFlags>(is, handler); } //! Initialize JSON text token-by-token parsing /*! */ void IterativeParseInit() { parseResult_.Clear(); state_ = IterativeParsingStartState; } //! Parse one token from JSON text /*! \tparam InputStream Type of input stream, implementing Stream concept \tparam Handler Type of handler, implementing Handler concept. \param is Input stream to be parsed. \param handler The handler to receive events. \return Whether the parsing is successful. */ template <unsigned parseFlags, typename InputStream, typename Handler> bool IterativeParseNext(InputStream& is, Handler& handler) { while (CEREAL_RAPIDJSON_LIKELY(is.Peek() != '\0')) { SkipWhitespaceAndComments<parseFlags>(is); Token t = Tokenize(is.Peek()); IterativeParsingState n = Predict(state_, t); IterativeParsingState d = Transit<parseFlags>(state_, t, n, is, handler); // If we've finished or hit an error... if (CEREAL_RAPIDJSON_UNLIKELY(IsIterativeParsingCompleteState(d))) { // Report errors. if (d == IterativeParsingErrorState) { HandleError(state_, is); return false; } // Transition to the finish state. CEREAL_RAPIDJSON_ASSERT(d == IterativeParsingFinishState); state_ = d; // If StopWhenDone is not set... if (!(parseFlags & kParseStopWhenDoneFlag)) { // ... and extra non-whitespace data is found... SkipWhitespaceAndComments<parseFlags>(is); if (is.Peek() != '\0') { // ... this is considered an error. HandleError(state_, is); return false; } } // Success! We are done! return true; } // Transition to the new state. state_ = d; // If we parsed anything other than a delimiter, we invoked the handler, so we can return true now. if (!IsIterativeParsingDelimiterState(n)) return true; } // We reached the end of file. stack_.Clear(); if (state_ != IterativeParsingFinishState) { HandleError(state_, is); return false; } return true; } //! Check if token-by-token parsing JSON text is complete /*! \return Whether the JSON has been fully decoded. */ CEREAL_RAPIDJSON_FORCEINLINE bool IterativeParseComplete() const { return IsIterativeParsingCompleteState(state_); } //! Whether a parse error has occurred in the last parsing. bool HasParseError() const { return parseResult_.IsError(); } //! Get the \ref ParseErrorCode of last parsing. ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); } //! Get the position of last parsing error in input, 0 otherwise. size_t GetErrorOffset() const { return parseResult_.Offset(); } protected: void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); } private: // Prohibit copy constructor & assignment operator. GenericReader(const GenericReader&); GenericReader& operator=(const GenericReader&); void ClearStack() { stack_.Clear(); } // clear stack on any exit from ParseStream, e.g. due to exception struct ClearStackOnExit { explicit ClearStackOnExit(GenericReader& r) : r_(r) {} ~ClearStackOnExit() { r_.ClearStack(); } private: GenericReader& r_; ClearStackOnExit(const ClearStackOnExit&); ClearStackOnExit& operator=(const ClearStackOnExit&); }; template<unsigned parseFlags, typename InputStream> void SkipWhitespaceAndComments(InputStream& is) { SkipWhitespace(is); if (parseFlags & kParseCommentsFlag) { while (CEREAL_RAPIDJSON_UNLIKELY(Consume(is, '/'))) { if (Consume(is, '*')) { while (true) { if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() == '\0')) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); else if (Consume(is, '*')) { if (Consume(is, '/')) break; } else is.Take(); } } else if (CEREAL_RAPIDJSON_LIKELY(Consume(is, '/'))) while (is.Peek() != '\0' && is.Take() != '\n') {} else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); SkipWhitespace(is); } } } // Parse object: { string : value, ... } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseObject(InputStream& is, Handler& handler) { CEREAL_RAPIDJSON_ASSERT(is.Peek() == '{'); is.Take(); // Skip '{' if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartObject())) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, '}')) { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } for (SizeType memberCount = 0;;) { if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() != '"')) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); ParseString<parseFlags>(is, handler, true); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (CEREAL_RAPIDJSON_UNLIKELY(!Consume(is, ':'))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; ParseValue<parseFlags>(is, handler); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; ++memberCount; switch (is.Peek()) { case ',': is.Take(); SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; break; case '}': is.Take(); if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; default: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); break; // This useless break is only for making warning and coverage happy } if (parseFlags & kParseTrailingCommasFlag) { if (is.Peek() == '}') { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); is.Take(); return; } } } } // Parse array: [ value, ... ] template<unsigned parseFlags, typename InputStream, typename Handler> void ParseArray(InputStream& is, Handler& handler) { CEREAL_RAPIDJSON_ASSERT(is.Peek() == '['); is.Take(); // Skip '[' if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartArray())) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, ']')) { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } for (SizeType elementCount = 0;;) { ParseValue<parseFlags>(is, handler); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; ++elementCount; SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (Consume(is, ',')) { SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; } else if (Consume(is, ']')) { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); return; } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); if (parseFlags & kParseTrailingCommasFlag) { if (is.Peek() == ']') { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); is.Take(); return; } } } } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseNull(InputStream& is, Handler& handler) { CEREAL_RAPIDJSON_ASSERT(is.Peek() == 'n'); is.Take(); if (CEREAL_RAPIDJSON_LIKELY(Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l'))) { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Null())) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseTrue(InputStream& is, Handler& handler) { CEREAL_RAPIDJSON_ASSERT(is.Peek() == 't'); is.Take(); if (CEREAL_RAPIDJSON_LIKELY(Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e'))) { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Bool(true))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); } template<unsigned parseFlags, typename InputStream, typename Handler> void ParseFalse(InputStream& is, Handler& handler) { CEREAL_RAPIDJSON_ASSERT(is.Peek() == 'f'); is.Take(); if (CEREAL_RAPIDJSON_LIKELY(Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e'))) { if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Bool(false))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); } template<typename InputStream> CEREAL_RAPIDJSON_FORCEINLINE static bool Consume(InputStream& is, typename InputStream::Ch expect) { if (CEREAL_RAPIDJSON_LIKELY(is.Peek() == expect)) { is.Take(); return true; } else return false; } // Helper function to parse four hexadecimal digits in \uXXXX in ParseString(). template<typename InputStream> unsigned ParseHex4(InputStream& is, size_t escapeOffset) { unsigned codepoint = 0; for (int i = 0; i < 4; i++) { Ch c = is.Peek(); codepoint <<= 4; codepoint += static_cast<unsigned>(c); if (c >= '0' && c <= '9') codepoint -= '0'; else if (c >= 'A' && c <= 'F') codepoint -= 'A' - 10; else if (c >= 'a' && c <= 'f') codepoint -= 'a' - 10; else { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, escapeOffset); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0); } is.Take(); } return codepoint; } template <typename CharType> class StackStream { public: typedef CharType Ch; StackStream(internal::Stack<StackAllocator>& stack) : stack_(stack), length_(0) {} CEREAL_RAPIDJSON_FORCEINLINE void Put(Ch c) { *stack_.template Push<Ch>() = c; ++length_; } CEREAL_RAPIDJSON_FORCEINLINE void* Push(SizeType count) { length_ += count; return stack_.template Push<Ch>(count); } size_t Length() const { return length_; } Ch* Pop() { return stack_.template Pop<Ch>(length_); } private: StackStream(const StackStream&); StackStream& operator=(const StackStream&); internal::Stack<StackAllocator>& stack_; SizeType length_; }; // Parse string and generate String event. Different code paths for kParseInsituFlag. template<unsigned parseFlags, typename InputStream, typename Handler> void ParseString(InputStream& is, Handler& handler, bool isKey = false) { internal::StreamLocalCopy<InputStream> copy(is); InputStream& s(copy.s); CEREAL_RAPIDJSON_ASSERT(s.Peek() == '\"'); s.Take(); // Skip '\"' bool success = false; if (parseFlags & kParseInsituFlag) { typename InputStream::Ch *head = s.PutBegin(); ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; size_t length = s.PutEnd(head) - 1; CEREAL_RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head); success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false)); } else { StackStream<typename TargetEncoding::Ch> stackStream(stack_); ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; SizeType length = static_cast<SizeType>(stackStream.Length()) - 1; const typename TargetEncoding::Ch* const str = stackStream.Pop(); success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true)); } if (CEREAL_RAPIDJSON_UNLIKELY(!success)) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell()); } // Parse string to an output is // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation. template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream> CEREAL_RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) { //!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 static const char escape[256] = { Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/', Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0, 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 }; #undef Z16 //!@endcond for (;;) { // Scan and copy string before "\\\"" or < 0x20. This is an optional optimzation. if (!(parseFlags & kParseValidateEncodingFlag)) ScanCopyUnescapedString(is, os); Ch c = is.Peek(); if (CEREAL_RAPIDJSON_UNLIKELY(c == '\\')) { // Escape size_t escapeOffset = is.Tell(); // For invalid escaping, report the initial '\\' as error offset is.Take(); Ch e = is.Peek(); if ((sizeof(Ch) == 1 || unsigned(e) < 256) && CEREAL_RAPIDJSON_LIKELY(escape[static_cast<unsigned char>(e)])) { is.Take(); os.Put(static_cast<typename TEncoding::Ch>(escape[static_cast<unsigned char>(e)])); } else if (CEREAL_RAPIDJSON_LIKELY(e == 'u')) { // Unicode is.Take(); unsigned codepoint = ParseHex4(is, escapeOffset); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (CEREAL_RAPIDJSON_UNLIKELY(codepoint >= 0xD800 && codepoint <= 0xDBFF)) { // Handle UTF-16 surrogate pair if (CEREAL_RAPIDJSON_UNLIKELY(!Consume(is, '\\') || !Consume(is, 'u'))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); unsigned codepoint2 = ParseHex4(is, escapeOffset); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; if (CEREAL_RAPIDJSON_UNLIKELY(codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000; } TEncoding::Encode(os, codepoint); } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset); } else if (CEREAL_RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote is.Take(); os.Put('\0'); // null-terminate the string return; } else if (CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(c) < 0x20)) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF if (c == '\0') CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell()); else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell()); } else { size_t offset = is.Tell(); if (CEREAL_RAPIDJSON_UNLIKELY((parseFlags & kParseValidateEncodingFlag ? !Transcoder<SEncoding, TEncoding>::Validate(is, os) : !Transcoder<SEncoding, TEncoding>::Transcode(is, os)))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, offset); } } } template<typename InputStream, typename OutputStream> static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InputStream&, OutputStream&) { // Do nothing for generic version } #if defined(CEREAL_RAPIDJSON_SSE2) || defined(CEREAL_RAPIDJSON_SSE42) // StringStream -> StackStream<char> static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) { const char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; return; } else os.Put(*p++); // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped SizeType length; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast<SizeType>(__builtin_ffs(r) - 1); #endif if (length != 0) { char* q = reinterpret_cast<char*>(os.Push(length)); for (size_t i = 0; i < length; i++) q[i] = p[i]; p += length; } break; } _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s); } is.src_ = p; } // InsituStringStream -> InsituStringStream static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { CEREAL_RAPIDJSON_ASSERT(&is == &os); (void)os; if (is.src_ == is.dst_) { SkipUnescapedString(is); return; } char* p = is.src_; char *q = is.dst_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; is.dst_ = q; return; } else *q++ = *p++; // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (;; p += 16, q += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped size_t length; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast<size_t>(__builtin_ffs(r) - 1); #endif for (const char* pend = p + length; p != pend; ) *q++ = *p++; break; } _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s); } is.src_ = p; is.dst_ = q; } // When read/write pointers are the same for insitu stream, just skip unescaped characters static CEREAL_RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { CEREAL_RAPIDJSON_ASSERT(is.src_ == is.dst_); char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); for (; p != nextAligned; p++) if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = is.dst_ = p; return; } // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (;; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped size_t length; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); length = offset; #else length = static_cast<size_t>(__builtin_ffs(r) - 1); #endif p += length; break; } } is.src_ = is.dst_ = p; } #elif defined(CEREAL_RAPIDJSON_NEON) // StringStream -> StackStream<char> static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) { const char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; return; } else os.Put(*p++); // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (;; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract SizeType length = 0; bool escaped = false; if (low == 0) { if (high != 0) { unsigned lz = (unsigned)__builtin_clzll(high);; length = 8 + (lz >> 3); escaped = true; } } else { unsigned lz = (unsigned)__builtin_clzll(low);; length = lz >> 3; escaped = true; } if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped if (length != 0) { char* q = reinterpret_cast<char*>(os.Push(length)); for (size_t i = 0; i < length; i++) q[i] = p[i]; p += length; } break; } vst1q_u8(reinterpret_cast<uint8_t *>(os.Push(16)), s); } is.src_ = p; } // InsituStringStream -> InsituStringStream static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { CEREAL_RAPIDJSON_ASSERT(&is == &os); (void)os; if (is.src_ == is.dst_) { SkipUnescapedString(is); return; } char* p = is.src_; char *q = is.dst_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); while (p != nextAligned) if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = p; is.dst_ = q; return; } else *q++ = *p++; // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (;; p += 16, q += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract SizeType length = 0; bool escaped = false; if (low == 0) { if (high != 0) { unsigned lz = (unsigned)__builtin_clzll(high); length = 8 + (lz >> 3); escaped = true; } } else { unsigned lz = (unsigned)__builtin_clzll(low); length = lz >> 3; escaped = true; } if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped for (const char* pend = p + length; p != pend; ) { *q++ = *p++; } break; } vst1q_u8(reinterpret_cast<uint8_t *>(q), s); } is.src_ = p; is.dst_ = q; } // When read/write pointers are the same for insitu stream, just skip unescaped characters static CEREAL_RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { CEREAL_RAPIDJSON_ASSERT(is.src_ == is.dst_); char* p = is.src_; // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); for (; p != nextAligned; p++) if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { is.src_ = is.dst_ = p; return; } // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (;; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract if (low == 0) { if (high != 0) { int lz = __builtin_clzll(high); p += 8 + (lz >> 3); break; } } else { int lz = __builtin_clzll(low); p += lz >> 3; break; } } is.src_ = is.dst_ = p; } #endif // CEREAL_RAPIDJSON_NEON template<typename InputStream, bool backup, bool pushOnTake> class NumberStream; template<typename InputStream> class NumberStream<InputStream, false, false> { public: typedef typename InputStream::Ch Ch; NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; } CEREAL_RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); } CEREAL_RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); } CEREAL_RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); } CEREAL_RAPIDJSON_FORCEINLINE void Push(char) {} size_t Tell() { return is.Tell(); } size_t Length() { return 0; } const char* Pop() { return 0; } protected: NumberStream& operator=(const NumberStream&); InputStream& is; }; template<typename InputStream> class NumberStream<InputStream, true, false> : public NumberStream<InputStream, false, false> { typedef NumberStream<InputStream, false, false> Base; public: NumberStream(GenericReader& reader, InputStream& s) : Base(reader, s), stackStream(reader.stack_) {} CEREAL_RAPIDJSON_FORCEINLINE Ch TakePush() { stackStream.Put(static_cast<char>(Base::is.Peek())); return Base::is.Take(); } CEREAL_RAPIDJSON_FORCEINLINE void Push(char c) { stackStream.Put(c); } size_t Length() { return stackStream.Length(); } const char* Pop() { stackStream.Put('\0'); return stackStream.Pop(); } private: StackStream<char> stackStream; }; template<typename InputStream> class NumberStream<InputStream, true, true> : public NumberStream<InputStream, true, false> { typedef NumberStream<InputStream, true, false> Base; public: NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {} CEREAL_RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); } }; template<unsigned parseFlags, typename InputStream, typename Handler> void ParseNumber(InputStream& is, Handler& handler) { internal::StreamLocalCopy<InputStream> copy(is); NumberStream<InputStream, ((parseFlags & kParseNumbersAsStringsFlag) != 0) ? ((parseFlags & kParseInsituFlag) == 0) : ((parseFlags & kParseFullPrecisionFlag) != 0), (parseFlags & kParseNumbersAsStringsFlag) != 0 && (parseFlags & kParseInsituFlag) == 0> s(*this, copy.s); size_t startOffset = s.Tell(); double d = 0.0; bool useNanOrInf = false; // Parse minus bool minus = Consume(s, '-'); // Parse int: zero / ( digit1-9 *DIGIT ) unsigned i = 0; uint64_t i64 = 0; bool use64bit = false; int significandDigit = 0; if (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() == '0')) { i = 0; s.TakePush(); } else if (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '1' && s.Peek() <= '9')) { i = static_cast<unsigned>(s.TakePush() - '0'); if (minus) while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (CEREAL_RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648 if (CEREAL_RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) { i64 = i; use64bit = true; break; } } i = i * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } else while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (CEREAL_RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295 if (CEREAL_RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) { i64 = i; use64bit = true; break; } } i = i * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } } // Parse NaN or Infinity here else if ((parseFlags & kParseNanAndInfFlag) && CEREAL_RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) { if (Consume(s, 'N')) { if (Consume(s, 'a') && Consume(s, 'N')) { d = std::numeric_limits<double>::quiet_NaN(); useNanOrInf = true; } } else if (CEREAL_RAPIDJSON_LIKELY(Consume(s, 'I'))) { if (Consume(s, 'n') && Consume(s, 'f')) { d = (minus ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity()); useNanOrInf = true; if (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n') && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) { CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); } } } if (CEREAL_RAPIDJSON_UNLIKELY(!useNanOrInf)) { CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); } } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); // Parse 64bit int bool useDouble = false; if (use64bit) { if (minus) while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (CEREAL_RAPIDJSON_UNLIKELY(i64 >= CEREAL_RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808 if (CEREAL_RAPIDJSON_LIKELY(i64 != CEREAL_RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) { d = static_cast<double>(i64); useDouble = true; break; } i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } else while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (CEREAL_RAPIDJSON_UNLIKELY(i64 >= CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999))) // 2^64 - 1 = 18446744073709551615 if (CEREAL_RAPIDJSON_LIKELY(i64 != CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) { d = static_cast<double>(i64); useDouble = true; break; } i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0'); significandDigit++; } } // Force double for big integer if (useDouble) { while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { d = d * 10 + (s.TakePush() - '0'); } } // Parse frac = decimal-point 1*DIGIT int expFrac = 0; size_t decimalPosition; if (Consume(s, '.')) { decimalPosition = s.Length(); if (CEREAL_RAPIDJSON_UNLIKELY(!(s.Peek() >= '0' && s.Peek() <= '9'))) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell()); if (!useDouble) { #if CEREAL_RAPIDJSON_64BIT // Use i64 to store significand in 64-bit architecture if (!use64bit) i64 = i; while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (i64 > CEREAL_RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path break; else { i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0'); --expFrac; if (i64 != 0) significandDigit++; } } d = static_cast<double>(i64); #else // Use double to store significand in 32-bit architecture d = static_cast<double>(use64bit ? i64 : i); #endif useDouble = true; } while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { if (significandDigit < 17) { d = d * 10.0 + (s.TakePush() - '0'); --expFrac; if (CEREAL_RAPIDJSON_LIKELY(d > 0.0)) significandDigit++; } else s.TakePush(); } } else decimalPosition = s.Length(); // decimal position at the end of integer. // Parse exp = e [ minus / plus ] 1*DIGIT int exp = 0; if (Consume(s, 'e') || Consume(s, 'E')) { if (!useDouble) { d = static_cast<double>(use64bit ? i64 : i); useDouble = true; } bool expMinus = false; if (Consume(s, '+')) ; else if (Consume(s, '-')) expMinus = true; if (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = static_cast<int>(s.Take() - '0'); if (expMinus) { // (exp + expFrac) must not underflow int => we're detecting when -exp gets // dangerously close to INT_MIN (a pessimistic next digit 9 would push it into // underflow territory): // // -(exp * 10 + 9) + expFrac >= INT_MIN // <=> exp <= (expFrac - INT_MIN - 9) / 10 CEREAL_RAPIDJSON_ASSERT(expFrac <= 0); int maxExp = (expFrac + 2147483639) / 10; while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = exp * 10 + static_cast<int>(s.Take() - '0'); if (CEREAL_RAPIDJSON_UNLIKELY(exp > maxExp)) { while (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent s.Take(); } } } else { // positive exp int maxExp = 308 - expFrac; while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { exp = exp * 10 + static_cast<int>(s.Take() - '0'); if (CEREAL_RAPIDJSON_UNLIKELY(exp > maxExp)) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); } } } else CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell()); if (expMinus) exp = -exp; } // Finish parsing, call event according to the type of number. bool cont = true; if (parseFlags & kParseNumbersAsStringsFlag) { if (parseFlags & kParseInsituFlag) { s.Pop(); // Pop stack no matter if it will be used or not. typename InputStream::Ch* head = is.PutBegin(); const size_t length = s.Tell() - startOffset; CEREAL_RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); // unable to insert the \0 character here, it will erase the comma after this number const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head); cont = handler.RawNumber(str, SizeType(length), false); } else { SizeType numCharsToCopy = static_cast<SizeType>(s.Length()); StringStream srcStream(s.Pop()); StackStream<typename TargetEncoding::Ch> dstStream(stack_); while (numCharsToCopy--) { Transcoder<UTF8<>, TargetEncoding>::Transcode(srcStream, dstStream); } dstStream.Put('\0'); const typename TargetEncoding::Ch* str = dstStream.Pop(); const SizeType length = static_cast<SizeType>(dstStream.Length()) - 1; cont = handler.RawNumber(str, SizeType(length), true); } } else { size_t length = s.Length(); const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not. if (useDouble) { int p = exp + expFrac; if (parseFlags & kParseFullPrecisionFlag) d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp); else d = internal::StrtodNormalPrecision(d, p); // Use > max, instead of == inf, to fix bogus warning -Wfloat-equal if (d > (std::numeric_limits<double>::max)()) { // Overflow // TODO: internal::StrtodX should report overflow (or underflow) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); } cont = handler.Double(minus ? -d : d); } else if (useNanOrInf) { cont = handler.Double(d); } else { if (use64bit) { if (minus) cont = handler.Int64(static_cast<int64_t>(~i64 + 1)); else cont = handler.Uint64(i64); } else { if (minus) cont = handler.Int(static_cast<int32_t>(~i + 1)); else cont = handler.Uint(i); } } } if (CEREAL_RAPIDJSON_UNLIKELY(!cont)) CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, startOffset); } // Parse any JSON value template<unsigned parseFlags, typename InputStream, typename Handler> void ParseValue(InputStream& is, Handler& handler) { switch (is.Peek()) { case 'n': ParseNull <parseFlags>(is, handler); break; case 't': ParseTrue <parseFlags>(is, handler); break; case 'f': ParseFalse <parseFlags>(is, handler); break; case '"': ParseString<parseFlags>(is, handler); break; case '{': ParseObject<parseFlags>(is, handler); break; case '[': ParseArray <parseFlags>(is, handler); break; default : ParseNumber<parseFlags>(is, handler); break; } } // Iterative Parsing // States enum IterativeParsingState { IterativeParsingFinishState = 0, // sink states at top IterativeParsingErrorState, // sink states at top IterativeParsingStartState, // Object states IterativeParsingObjectInitialState, IterativeParsingMemberKeyState, IterativeParsingMemberValueState, IterativeParsingObjectFinishState, // Array states IterativeParsingArrayInitialState, IterativeParsingElementState, IterativeParsingArrayFinishState, // Single value state IterativeParsingValueState, // Delimiter states (at bottom) IterativeParsingElementDelimiterState, IterativeParsingMemberDelimiterState, IterativeParsingKeyValueDelimiterState, cIterativeParsingStateCount }; // Tokens enum Token { LeftBracketToken = 0, RightBracketToken, LeftCurlyBracketToken, RightCurlyBracketToken, CommaToken, ColonToken, StringToken, FalseToken, TrueToken, NullToken, NumberToken, kTokenCount }; CEREAL_RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) const { //!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN #define N NumberToken #define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N // Maps from ASCII to Token static const unsigned char tokenMap[256] = { N16, // 00~0F N16, // 10~1F N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F N16, // 40~4F N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF }; #undef N #undef N16 //!@endcond if (sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) return static_cast<Token>(tokenMap[static_cast<unsigned char>(c)]); else return NumberToken; } CEREAL_RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) const { // current state x one lookahead token -> new state static const char G[cIterativeParsingStateCount][kTokenCount] = { // Finish(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // Error(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // Start { IterativeParsingArrayInitialState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingValueState, // String IterativeParsingValueState, // False IterativeParsingValueState, // True IterativeParsingValueState, // Null IterativeParsingValueState // Number }, // ObjectInitial { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingObjectFinishState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingMemberKeyState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // MemberKey { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingKeyValueDelimiterState, // Colon IterativeParsingErrorState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // MemberValue { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingObjectFinishState, // Right curly bracket IterativeParsingMemberDelimiterState, // Comma IterativeParsingErrorState, // Colon IterativeParsingErrorState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // ObjectFinish(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // ArrayInitial { IterativeParsingArrayInitialState, // Left bracket(push Element state) IterativeParsingArrayFinishState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket(push Element state) IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingElementState, // String IterativeParsingElementState, // False IterativeParsingElementState, // True IterativeParsingElementState, // Null IterativeParsingElementState // Number }, // Element { IterativeParsingErrorState, // Left bracket IterativeParsingArrayFinishState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingErrorState, // Right curly bracket IterativeParsingElementDelimiterState, // Comma IterativeParsingErrorState, // Colon IterativeParsingErrorState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // ArrayFinish(sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // Single Value (sink state) { IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState }, // ElementDelimiter { IterativeParsingArrayInitialState, // Left bracket(push Element state) IterativeParsingArrayFinishState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket(push Element state) IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingElementState, // String IterativeParsingElementState, // False IterativeParsingElementState, // True IterativeParsingElementState, // Null IterativeParsingElementState // Number }, // MemberDelimiter { IterativeParsingErrorState, // Left bracket IterativeParsingErrorState, // Right bracket IterativeParsingErrorState, // Left curly bracket IterativeParsingObjectFinishState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingMemberKeyState, // String IterativeParsingErrorState, // False IterativeParsingErrorState, // True IterativeParsingErrorState, // Null IterativeParsingErrorState // Number }, // KeyValueDelimiter { IterativeParsingArrayInitialState, // Left bracket(push MemberValue state) IterativeParsingErrorState, // Right bracket IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state) IterativeParsingErrorState, // Right curly bracket IterativeParsingErrorState, // Comma IterativeParsingErrorState, // Colon IterativeParsingMemberValueState, // String IterativeParsingMemberValueState, // False IterativeParsingMemberValueState, // True IterativeParsingMemberValueState, // Null IterativeParsingMemberValueState // Number }, }; // End of G return static_cast<IterativeParsingState>(G[state][token]); } // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit(). // May return a new state on state pop. template <unsigned parseFlags, typename InputStream, typename Handler> CEREAL_RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) { (void)token; switch (dst) { case IterativeParsingErrorState: return dst; case IterativeParsingObjectInitialState: case IterativeParsingArrayInitialState: { // Push the state(Element or MemeberValue) if we are nested in another array or value of member. // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop. IterativeParsingState n = src; if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState) n = IterativeParsingElementState; else if (src == IterativeParsingKeyValueDelimiterState) n = IterativeParsingMemberValueState; // Push current state. *stack_.template Push<SizeType>(1) = n; // Initialize and push the member/element count. *stack_.template Push<SizeType>(1) = 0; // Call handler bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray(); // On handler short circuits the parsing. if (!hr) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); return IterativeParsingErrorState; } else { is.Take(); return dst; } } case IterativeParsingMemberKeyState: ParseString<parseFlags>(is, handler, true); if (HasParseError()) return IterativeParsingErrorState; else return dst; case IterativeParsingKeyValueDelimiterState: CEREAL_RAPIDJSON_ASSERT(token == ColonToken); is.Take(); return dst; case IterativeParsingMemberValueState: // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. ParseValue<parseFlags>(is, handler); if (HasParseError()) { return IterativeParsingErrorState; } return dst; case IterativeParsingElementState: // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. ParseValue<parseFlags>(is, handler); if (HasParseError()) { return IterativeParsingErrorState; } return dst; case IterativeParsingMemberDelimiterState: case IterativeParsingElementDelimiterState: is.Take(); // Update member/element count. *stack_.template Top<SizeType>() = *stack_.template Top<SizeType>() + 1; return dst; case IterativeParsingObjectFinishState: { // Transit from delimiter is only allowed when trailing commas are enabled if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingMemberDelimiterState) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell()); return IterativeParsingErrorState; } // Get member count. SizeType c = *stack_.template Pop<SizeType>(1); // If the object is not empty, count the last member. if (src == IterativeParsingMemberValueState) ++c; // Restore the state. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1)); // Transit to Finish state if this is the topmost scope. if (n == IterativeParsingStartState) n = IterativeParsingFinishState; // Call handler bool hr = handler.EndObject(c); // On handler short circuits the parsing. if (!hr) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); return IterativeParsingErrorState; } else { is.Take(); return n; } } case IterativeParsingArrayFinishState: { // Transit from delimiter is only allowed when trailing commas are enabled if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingElementDelimiterState) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell()); return IterativeParsingErrorState; } // Get element count. SizeType c = *stack_.template Pop<SizeType>(1); // If the array is not empty, count the last element. if (src == IterativeParsingElementState) ++c; // Restore the state. IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1)); // Transit to Finish state if this is the topmost scope. if (n == IterativeParsingStartState) n = IterativeParsingFinishState; // Call handler bool hr = handler.EndArray(c); // On handler short circuits the parsing. if (!hr) { CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); return IterativeParsingErrorState; } else { is.Take(); return n; } } default: // This branch is for IterativeParsingValueState actually. // Use `default:` rather than // `case IterativeParsingValueState:` is for code coverage. // The IterativeParsingStartState is not enumerated in this switch-case. // It is impossible for that case. And it can be caught by following assertion. // The IterativeParsingFinishState is not enumerated in this switch-case either. // It is a "derivative" state which cannot triggered from Predict() directly. // Therefore it cannot happen here. And it can be caught by following assertion. CEREAL_RAPIDJSON_ASSERT(dst == IterativeParsingValueState); // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. ParseValue<parseFlags>(is, handler); if (HasParseError()) { return IterativeParsingErrorState; } return IterativeParsingFinishState; } } template <typename InputStream> void HandleError(IterativeParsingState src, InputStream& is) { if (HasParseError()) { // Error flag has been set. return; } switch (src) { case IterativeParsingStartState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); return; case IterativeParsingFinishState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); return; case IterativeParsingObjectInitialState: case IterativeParsingMemberDelimiterState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); return; case IterativeParsingMemberKeyState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); return; case IterativeParsingMemberValueState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); return; case IterativeParsingKeyValueDelimiterState: case IterativeParsingArrayInitialState: case IterativeParsingElementDelimiterState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); return; default: CEREAL_RAPIDJSON_ASSERT(src == IterativeParsingElementState); CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); return; } } CEREAL_RAPIDJSON_FORCEINLINE bool IsIterativeParsingDelimiterState(IterativeParsingState s) const { return s >= IterativeParsingElementDelimiterState; } CEREAL_RAPIDJSON_FORCEINLINE bool IsIterativeParsingCompleteState(IterativeParsingState s) const { return s <= IterativeParsingErrorState; } template <unsigned parseFlags, typename InputStream, typename Handler> ParseResult IterativeParse(InputStream& is, Handler& handler) { parseResult_.Clear(); ClearStackOnExit scope(*this); IterativeParsingState state = IterativeParsingStartState; SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); while (is.Peek() != '\0') { Token t = Tokenize(is.Peek()); IterativeParsingState n = Predict(state, t); IterativeParsingState d = Transit<parseFlags>(state, t, n, is, handler); if (d == IterativeParsingErrorState) { HandleError(state, is); break; } state = d; // Do not further consume streams if a root JSON has been parsed. if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState) break; SkipWhitespaceAndComments<parseFlags>(is); CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); } // Handle the end of file. if (state != IterativeParsingFinishState) HandleError(state, is); return parseResult_; } static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string. internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing. ParseResult parseResult_; IterativeParsingState state_; }; // class GenericReader //! Reader with UTF8 encoding and default allocator. typedef GenericReader<UTF8<>, UTF8<> > Reader; CEREAL_RAPIDJSON_NAMESPACE_END #if defined(__clang__) || defined(_MSC_VER) CEREAL_RAPIDJSON_DIAG_POP #endif #ifdef __GNUC__ CEREAL_RAPIDJSON_DIAG_POP #endif #endif // CEREAL_RAPIDJSON_READER_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/bin/run-ci-ldc93s1_new_sdb_csv.sh
#!/bin/sh set -xe ldc93s1_dir="./data/smoke_test" ldc93s1_csv="${ldc93s1_dir}/ldc93s1.csv" ldc93s1_sdb="${ldc93s1_dir}/ldc93s1.sdb" epoch_count=$1 audio_sample_rate=$2 if [ ! -f "${ldc93s1_dir}/ldc93s1.csv" ]; then echo "Downloading and preprocessing LDC93S1 example data, saving in ${ldc93s1_dir}." python -u bin/import_ldc93s1.py ${ldc93s1_dir} fi; if [ ! -f "${ldc93s1_dir}/ldc93s1.sdb" ]; then echo "Converting LDC93S1 example data, saving to ${ldc93s1_sdb}." python -u bin/data_set_tool.py --sources ${ldc93s1_csv} --target ${ldc93s1_sdb} fi; # Force only one visible device because we have a single-sample dataset # and when trying to run on multiple devices (like GPUs), this will break export CUDA_VISIBLE_DEVICES=0 python -u train.py --alphabet_config_path "data/alphabet.txt" \ --show_progressbar false --early_stop false \ --train_files ${ldc93s1_sdb} ${ldc93s1_csv} --train_batch_size 1 \ --feature_cache '/tmp/ldc93s1_cache_sdb_csv' \ --dev_files ${ldc93s1_sdb} ${ldc93s1_csv} --dev_batch_size 1 \ --test_files ${ldc93s1_sdb} ${ldc93s1_csv} --test_batch_size 1 \ --n_hidden 100 --epochs $epoch_count \ --max_to_keep 1 --checkpoint_dir '/tmp/ckpt_sdb_csv' \ --learning_rate 0.001 --dropout_rate 0.05 --export_dir '/tmp/train_sdb_csv' \ --scorer_path 'data/smoke_test/pruned_lm.scorer' \ --audio_sample_rate ${audio_sample_rate}
0
coqui_public_repos/coqui-py
coqui_public_repos/coqui-py/test/test_something.py
import pytest # pytest forces us to redefine the `mock` global function as a parameter of # the test cases as that's how you request a fixture, so we disable this lint # globally in this file. # pylint: disable=redefined-outer-name @pytest.fixture def mock(): # Setup my_obj = {"what": "fixture?!?"} # Yield the ready to be used fixture object yield my_obj # Cleanup # my_obj.clean_resources() def test_something(mock): # response = mock.do_something() # assert response == "expectation" assert mock["what"] == "fixture?!?"
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/m4/ltsugar.m4
# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004-2005, 2007-2008, 2011-2015 Free Software # Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59, which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ])
0
coqui_public_repos/TTS/TTS/tts/utils
coqui_public_repos/TTS/TTS/tts/utils/text/punctuation.py
import collections import re from enum import Enum import six _DEF_PUNCS = ';:,.!?¡¿—…"«»“”' _PUNC_IDX = collections.namedtuple("_punc_index", ["punc", "position"]) class PuncPosition(Enum): """Enum for the punctuations positions""" BEGIN = 0 END = 1 MIDDLE = 2 class Punctuation: """Handle punctuations in text. Just strip punctuations from text or strip and restore them later. Args: puncs (str): The punctuations to be processed. Defaults to `_DEF_PUNCS`. Example: >>> punc = Punctuation() >>> punc.strip("This is. example !") 'This is example' >>> text_striped, punc_map = punc.strip_to_restore("This is. example !") >>> ' '.join(text_striped) 'This is example' >>> text_restored = punc.restore(text_striped, punc_map) >>> text_restored[0] 'This is. example !' """ def __init__(self, puncs: str = _DEF_PUNCS): self.puncs = puncs @staticmethod def default_puncs(): """Return default set of punctuations.""" return _DEF_PUNCS @property def puncs(self): return self._puncs @puncs.setter def puncs(self, value): if not isinstance(value, six.string_types): raise ValueError("[!] Punctuations must be of type str.") self._puncs = "".join(list(dict.fromkeys(list(value)))) # remove duplicates without changing the oreder self.puncs_regular_exp = re.compile(rf"(\s*[{re.escape(self._puncs)}]+\s*)+") def strip(self, text): """Remove all the punctuations by replacing with `space`. Args: text (str): The text to be processed. Example:: "This is. example !" -> "This is example " """ return re.sub(self.puncs_regular_exp, " ", text).rstrip().lstrip() def strip_to_restore(self, text): """Remove punctuations from text to restore them later. Args: text (str): The text to be processed. Examples :: "This is. example !" -> [["This is", "example"], [".", "!"]] """ text, puncs = self._strip_to_restore(text) return text, puncs def _strip_to_restore(self, text): """Auxiliary method for Punctuation.preserve()""" matches = list(re.finditer(self.puncs_regular_exp, text)) if not matches: return [text], [] # the text is only punctuations if len(matches) == 1 and matches[0].group() == text: return [], [_PUNC_IDX(text, PuncPosition.BEGIN)] # build a punctuation map to be used later to restore punctuations puncs = [] for match in matches: position = PuncPosition.MIDDLE if match == matches[0] and text.startswith(match.group()): position = PuncPosition.BEGIN elif match == matches[-1] and text.endswith(match.group()): position = PuncPosition.END puncs.append(_PUNC_IDX(match.group(), position)) # convert str text to a List[str], each item is separated by a punctuation splitted_text = [] for idx, punc in enumerate(puncs): split = text.split(punc.punc) prefix, suffix = split[0], punc.punc.join(split[1:]) text = suffix if prefix == "": # We don't want to insert an empty string in case of initial punctuation continue splitted_text.append(prefix) # if the text does not end with a punctuation, add it to the last item if idx == len(puncs) - 1 and len(suffix) > 0: splitted_text.append(suffix) return splitted_text, puncs @classmethod def restore(cls, text, puncs): """Restore punctuation in a text. Args: text (str): The text to be processed. puncs (List[str]): The list of punctuations map to be used for restoring. Examples :: ['This is', 'example'], ['.', '!'] -> "This is. example!" """ return cls._restore(text, puncs) @classmethod def _restore(cls, text, puncs): # pylint: disable=too-many-return-statements """Auxiliary method for Punctuation.restore()""" if not puncs: return text # nothing have been phonemized, returns the puncs alone if not text: return ["".join(m.punc for m in puncs)] current = puncs[0] if current.position == PuncPosition.BEGIN: return cls._restore([current.punc + text[0]] + text[1:], puncs[1:]) if current.position == PuncPosition.END: return [text[0] + current.punc] + cls._restore(text[1:], puncs[1:]) # POSITION == MIDDLE if len(text) == 1: # pragma: nocover # a corner case where the final part of an intermediate # mark (I) has not been phonemized return cls._restore([text[0] + current.punc], puncs[1:]) return cls._restore([text[0] + current.punc + text[1]] + text[2:], puncs[1:]) # if __name__ == "__main__": # punc = Punctuation() # text = "This is. This is, example!" # print(punc.strip(text)) # split_text, puncs = punc.strip_to_restore(text) # print(split_text, " ---- ", puncs) # restored_text = punc.restore(split_text, puncs) # print(restored_text)
0